题目:
Given an array nums
of n integers where n > 1, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Example:
Input:[1,2,3,4]
Output:[24,12,8,6]
Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
先写了个用除法的版本,其实还是有些corner case要注意的,比如如果数组中出现了0。出现0还分两种情况,如果只出现了一次,那只有在它那里的result不是0,如果超过一次,那就全是0了。
Runtime: 1 ms, faster than 99.99% of Java online submissions for Product of Array Except Self.
Memory Usage: 47.3 MB, less than 96.15% of Java online submissions for Product of Array Except Self.
class Solution {
public int[] productExceptSelf(int[] nums) {
int all = 1;
int zeroCount = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
zeroCount++;
} else {
all *= nums[i];
}
}
int[] result = new int[nums.length];
if (zeroCount > 1) {
return result;
}
for (int i = 0; i < nums.length; i++) {
if (zeroCount == 0) {
result[i] = all / nums[i];
} else {
if (nums[i] == 0) {
result[i] = all;
} else {
result[i] = 0;
}
}
}
return result;
}
}
然后是不用除法的做法。我们可以把整个数组分成两半,left,nums[i],和right。分别求出左半边和右半边乘积,最后相乘就是了。具体的左半边和右半边可以用数组表示,left[i]表示从[0, i - 1]的乘积,right[i]表示[i + 1, len - 1]的乘积。写代码的时候需要注意下标,首先要将left[0]和right[len - 1]初始化成1,然后再for循环里更新left[i]和right[len - i - 1],注意left[i]的乘积是要left[i - 1]乘i - 1,right也同理。
Runtime: 2 ms, faster than 32.44% of Java online submissions for Product of Array Except Self.
Memory Usage: 47.7 MB, less than 80.91% of Java online submissions for Product of Array Except Self.
class Solution {
public int[] productExceptSelf(int[] nums) {
int len = nums.length;
int[] left = new int[len];
left[0] = 1;
int[] right = new int[len];
right[len - 1] = 1;
for (int i = 1; i < len; i++) {
left[i] = left[i - 1] * nums[i - 1];
right[len - i - 1] = right[len - i] * nums[len - i];
}
int[] result = new int[len];
for (int i = 0; i < len; i++) {
result[i] = left[i] * right[i];
}
return result;
}
}