Product of Array Except Self
题目地址:
https://leetcode.com/problems/product-of-array-except-self/#/description
题目:
解题思路:
这道题就是两个loop。第一个loop是将每一个位置的数置为自己index之前的数的乘积,第二个loop首先要有一个right的数,首先更新rst的数,然后更新right。
代码:
https://leetcode.com/problems/product-of-array-except-self/#/description
题目:
Given an array of n integers where n > 1,
nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Solve it without division and in O(n).
For example, given
[1,2,3,4], return [24,12,8,6].
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
解题思路:
这道题就是两个loop。第一个loop是将每一个位置的数置为自己index之前的数的乘积,第二个loop首先要有一个right的数,首先更新rst的数,然后更新right。
代码:
public int[] productExceptSelf(int[] nums) { if(nums == null || nums.length == 0){ return null; } int[] rst = new int[nums.length]; rst[0] = 1; for(int i = 1; i <= nums.length - 1; i++){ rst[i] = nums[i - 1] * rst[i - 1]; } int right = 1; for(int i = nums.length - 1; i >= 0; i--){ rst[i] *= right; right = right * nums[i]; }

Comments
Post a Comment