LeetCode Problem Link: https://leetcode.com/problems/product-of-array-except-self/description/
Solution:
class Solution {
public int[] productExceptSelf(int[] nums) {
int length = nums.length;
int[] result = new int[length];
// Store the product of left side.
int tmp = 1;
for (int i = 0; i < length; i++) {
result[i] = tmp;
tmp *= nums[i];
}
// Multiply the product of right side.
tmp = nums[length - 1];
for (int i = length - 2; i >= 0; i--) {
result[i] *= tmp;
tmp *= nums[i];
}
return result;
}
}
Complexity:
O(n) Time Complexity
O(1) Space Complexity (The space for storing result does not count)
Result:
Run Time 2ms
Beats 25% users
Solution:
class Solution {
public int[] productExceptSelf(int[] nums) {
int length = nums.length;
int[] result = new int[length];
// Store the product of left side.
int tmp = 1;
for (int i = 0; i < length; i++) {
result[i] = tmp;
tmp *= nums[i];
}
// Multiply the product of right side.
tmp = nums[length - 1];
for (int i = length - 2; i >= 0; i--) {
result[i] *= tmp;
tmp *= nums[i];
}
return result;
}
}
Complexity:
O(n) Time Complexity
O(1) Space Complexity (The space for storing result does not count)
Result:
Run Time 2ms
Beats 25% users
留言
張貼留言