public class Solution {
public int[] productExceptSelf(int[] nums) {
/*
https://leetcode.com/discuss/46104/simple-java-solution-in-o-n-without-extra-space
Given numbers [2, 3, 4, 5], regarding the third number 4, the product of array except 4 is 2*3*5 which consists of two parts: left 2*3 and right 5. The product is left*right. We can get lefts and rights:
Numbers: 2 3 4 5
Lefts: 2 2*3 2*3*4
Rights: 3*4*5 4*5 5
Let’s fill the empty with 1:
Numbers: 2 3 4 5
Lefts: 1 2 2*3 2*3*4
Rights: 3*4*5 4*5 5 1
We can calculate lefts and rights in 2 loops. The time complexity is O(n).
We store lefts in result array. If we allocate a new array for rights. The space complexity is O(n). To make it O(1), we just need to store it in a variable which is right in @lycjava3’s code.
*/
int n = nums.length;
int[] res = new int[n];
// Calculate lefts and store in res.
int left = 1;
for (int i = 0; i < n; i++) {
if (i > 0)
left = left * nums[i - 1];
res[i] = left;
}
// Calculate rights and the product from the end of the array.
int right = 1;
for (int i = n - 1; i >= 0; i--) {
if (i < n - 1)
right = right * nums[i + 1];
res[i] *= right;
}
return res;
}
public int[] productExceptSelf_sol2(int[] nums) {
/* https://leetcode.com/discuss/46104/simple-java-solution-in-o-n-without-extra-space
https://leetcode.com/discuss/53781/my-solution-beats-100%25-java-solutions
The product basically is calculated using the numbers before the current number
and the numbers after the current number. Thus, we can scan the array twice.
First, we calcuate the running product of the part before the current number.
Second, we calculate the running product of the part
after the current number through scanning from the end of the array.
*/
// scan array twice
int n = nums.length;
int[] res = new int[n];
res[0] = 1;
for (int i=1; i<n; i++) {
res[i] = res[i-1] * nums[i-1];
}
// scan from end
int right = 1;
for (int i=n-1; i >= 0; i--) {
res[i] *= right;
right *= nums[i];
}
return res;
}
}
238. Product of Array Except Self
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 题目描述 原题链接:Product of Array Except Self Given an array of ...
- 很有趣的思路,这道题难在思维的转换,需要好生思考,每一位的输出结果被该位分成前后两段,本质上讲从前和从后遍历没有区...
- Given an array of n integers where n > 1, nums, return an...
- Given an array of n integers where n > 1, nums, return an...
- Given an array of n integers where n > 1, nums, return a...