238. Product of Array Except Self
class Solution { public int[] productExceptSelf(int[] nums) { int[] right = new int[nums.length]; int[] left = new int[nums.length]; int[] result = new int[nums.length]; Arrays.fill(right, 1); Arrays.fill(left, 1); for(int i = nums.length - 2; i >= 0; i--){ right[i] = right[i+1] * nums[i+1]; } for(int j = 1; j < nums.length; j++){ left[j] = left[j-1] * nums[j-1]; } for(int s = 0; s < nums.length; s++){ result[s] = left[s] * right[s]; } return result; } } class Solution { public int[] productExceptSelf(int[] nums) { int[] result = new int[nums.length]; Arrays.fill(result, 1); for(int i = nums.length - 2; i >= 0; i--){ result[i] = result[i + 1] * nums[i + 1]; } int tmp = nums[0]; for(int j = 1; j < nums.length; j++){ result[j] = result[j] * tmp; tmp = tmp * nums[j]; } return result; } }
if concerned with 0, check the elements on the side first, the situation in the middle is handled
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]
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.)
posted on 2018-08-17 08:11 猪猪🐷 阅读(121) 评论(0) 收藏 举报
浙公网安备 33010602011771号