ID | Title | Difficulty | |
---|---|---|---|
Loading... |
238. Product of Array Except Self
Medium
LeetCode
Array, Prefix Sum
Problem
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.)
Code
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] res = new int[nums.length];
res[0] = 1;
int curr = nums[0];
for(int i = 1; i < nums.length; i++) {
res[i] = curr;
curr *= nums[i];
}
curr = nums[nums.length - 1];
for(int i = nums.length - 2; i >= 0; i--){
res[i] *= curr;
curr *= nums[i];
}
return res;
}
}
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
res = []
for i in range(len(nums)):
res.append(1)
curr = nums[0]
for i in range(1, len(nums)):
res[i] = curr
curr *= nums[i]
curr = nums[-1]
for i in range(len(nums) - 2, -1, -1):
res[i] *= curr
curr *= nums[i]
return res
按 <- 键看上一题!
237. Delete Node in a Linked List
按 -> 键看下一题!
239. Sliding Window Maximum