[LinkedIn] Array of products of all other numbers (except/without the current number ) (no division)
来源:互联网 发布:人工智能 创投 编辑:程序博客网 时间:2024/05/22 00:31
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.
先建立一个array A,从右到左遍历,A[i]是这个东西右边所有东西的product。
然后从左边开始遍历,maintain在i位置左边的乘积, 乘上A[i]即可。
public static int[] product(int[] input) { int[] rightProd = new int[input.length]; p = 1; for (int i = input.length - 1; i >= 0; i--) { rightProd[i] = p; p *= input[i]; } int[] resProd = new int[input.length]; int left = 1; for (int i = 0; i < input.length; i++) { resProd[i] = left * rightProd[i]; left *= input[i]; } return resProd; }
Another way, O(1) space
//here left is always the product on i's left //and right is always the product on length-1-i's right.public int[] products(int[] A) { if (A == null || A.length == 0) { return null; } int[] B = new int[A.length]; for (int i = 0; i < B.length; ++i) { B[i] = 1; } int left = 1, right = 1; for (int i = 0; i < A.length; ++i) { B[i] *= left; B[A.length-1-i] *= right; left *= A[i]; right *= A[A.length-1-i]; } return B;}
0 0
- [LinkedIn] Array of products of all other numbers (except/without the current number ) (no division)
- Given an array of numbers, return array of products of all other numbers (no division)
- CareerCup Fill the array with product of all numbers except the number in that cell
- Finding a number that repeats even no of times where all the other numbers repeat odd no of times
- Interview Return Products of All Other Elements in Array
- Given a sequence of numbers (or array).Find the maximum distance between all the same numbers.
- [Facebook] Products of all elements
- The 50 Best Tech Products of All Time
- leetCode No.238 Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- leetcode_Product of Array Except Self
- Product of Array Except Self
- 初学PHP如何在浏览器上显示东西
- 计算机组成原理--数制
- GDB使用方法
- 17x^2+16xy+17y^2=2250000(爱心函数)canvas实现代码(效果如图)
- Java操作符总结
- [LinkedIn] Array of products of all other numbers (except/without the current number ) (no division)
- FMDB的使用
- (四)Unity5.0新特性------音频混音器(转自官方博客)
- Django论坛系统LBForum(开源)
- WIFI 未整理的垃圾
- java转义字符
- Fragment里面的Viewpaper不显示内容不执行getItem的解决方案
- 创建交互式博客——jquery (4)
- Interview and English(2)