Version #1 从左往右扫一遍再从右往左扫一遍
O(1) Space
O(N) Time
三刷
100.00 %
class Solution {
public int[] productExceptSelf(int[] nums) {
if (nums == null || nums.length == 0) return new int[0];
int temp = 1;
int[] result = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
result[i] = temp;
temp *= nums[i];
}
temp = nums[nums.length - 1];
for (int i = nums.length - 2; i >= 0; i--) {
result[i] *= temp;
temp *= nums[i];
}
return result;
}
}
29.73 %
class Solution {
public int[] productExceptSelf(int[] nums) {
if (nums == null || nums.length == 0) return null;
int leftProduct = 1;
int rightProduct = 1;
int[] res = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
res[i] = leftProduct;
leftProduct *= nums[i];
}
for (int j = nums.length - 1; j >= 0; j--) {
res[j] = res[j] * rightProduct;
rightProduct *= nums[j];
}
return res;
}
}
二刷
class Solution {
public int[] productExceptSelf(int[] nums) {
if (nums == null || nums.length == 0) return nums;
int[] result = new int[nums.length];
int leftProduct = 1;
int rightProduct = 1;
for (int i = 0; i < nums.length; i++) {
result[i] = leftProduct;
leftProduct *= nums[i];
}
for (int j = nums.length - 1; j >= 0; j--) {
result[j] = rightProduct * result[j];
rightProduct *= nums[j];
}
return result;
}
}
No comments:
Post a Comment