[Facebook] Products of all elements
2016-01-12 11:10
253 查看
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)
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:
If you need to be O(1) in space too you can do this (which is less clear IMHO)
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 // This is the input int products_below ; p=1; for(int i=0;i<N;++i) { products_below[i]=p; p*=a[i]; } int products_above ; p=1; for(int i=N-1;i>=0;--i) { products_above[i]=p; p*=a[i]; } int products ; // 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 // This is the input int products ; // 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]; }
相关文章推荐
- [Google] Inorder Successor in Binary Search Tree, Solution
- [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
- [LeetCode] Surrounded Regions, Solution
- [LeetCode] Palindrome Partitioning, Solution
- [LeetCode] Palindrome Partitioning II, Solution
- [LeetCode] Two Sum, Solution
- [LeetCode] Longest Valid Parentheses, Solution
- [LeetCode] Merge Two Sorted Lists, Solution
- C#程序通过模板自动创建Word文档
- 使用UIImageView的画线方法
- python生成随机数组
- iOS 真机测试经常出现的不能运行的问题及解决方案
- Content Provider基础(一)初识和访问其它程序中数据的方法
- 关于 mysql中非null判断
- [LeetCode] Text Justification 解题报告