[Facebook] Products of all elements
来源:互联网 发布:内部优惠券提取软件 编辑:程序博客网 时间:2024/05/29 04:17
Given an array of numbers, nums, return an array of numbers products, where products[i] is the product of all nums[j], j != i.
Input : [1, 2, 3, 4, 5]
Output: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5), (1*2*3*4)]
= [120, 60, 40, 30, 24]
You must do this in O(N) without using division.
[Thoughts]
An explaination of polygenelubricants method is: The trick is to construct the arrays (in the case for 4 elements)
{ 1, a[0], a[0]*a[1], a[0]*a[1]*a[2], }
{ a[1]*a[2]*a[3], a[2]*a[3], a[3], 1, }
Both of which can be done in O(n) by starting at the left and right edges respectively.
Then multiplying the two arrays element by element gives the required result
My code would look something like this:
int a[N] // This is the input
int products_below[N];
p=1;
for(int i=0;i<N;++i)
{
products_below[i]=p;
p*=a[i];
}
int products_above[N];
p=1;
for(int i=N-1;i>=0;--i)
{
products_above[i]=p;
p*=a[i];
}
int products[N]; // This is the result
for(int i=0;i<N;++i)
{
products[i]=products_below[i]*products_above[i];
}
If you need to be O(1) in space too you can do this (which is less clear IMHO)
int a[N] // This is the input
int products[N];
// Get the products below the curent index
p=1;
for(int i=0;i<N;++i)
{
products[i]=p;
p*=a[i];
}
// Get the products above the curent index
p=1;
for(int i=N-1;i>=0;--i)
{
products[i]*=p;
p*=a[i];
}
0 0
- [Facebook] Products of all elements
- Interview Return Products of All Other Elements in Array
- The 50 Best Tech Products of All Time
- Best Tutorial of all products http://www.tutorialspdf.com/
- Find all max of elements of an array
- Find all max of elements of an array
- Given an array of numbers, return array of products of all other numbers (no division)
- [LinkedIn] Array of products of all other numbers (except/without the current number ) (no division)
- JSP for loop output all elements of an array
- Basic configuration of Products
- Main products of Acro Fluid
- find all pairs of elements in a balanced BST that sum to a certain number
- 【AWK】Scanning all Elements of an Array--每日一译2013-02-05
- Ruby: How to find all indices of elements that match a given condition?
- Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral or
- remove all the same elements
- Elements of Set Theory_Errata
- Elements of Information Theory
- [LeetCode] Convert Sorted List to Binary Search Tree, Solution
- [LeetCode] Count and Say, Solution
- [LeetCode] Decode Ways, Solution
- [FaceBook] Hanoi Moves, Solution
- git查看本地和创建分支、上传分支、提交代码到分支、删除分支等,git分支
- [Facebook] Products of all elements
- [Google] Inorder Successor in Binary Search Tree, Solution
- 基于jq 滚动条到底加载更多的方法
- [Google] URL query with wild card
- [Yahoo] Cloest palindrome number, Solution
- [LeetCode] Valid Palindrome, Solution
- [LeetCode] Word Ladder II, Solution
- [LeetCode] Sum Root to Leaf Numbers, Solution
- [LeetCode] Longest Consecutive Sequence, Solution