leetcode——Product of Array Except Self

来源:互联网 发布:sql语句销量榜 编辑:程序博客网 时间:2024/05/16 06:44

题目

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.)

思路

题目的意思是,要将这整个数组,针对每一个数字,求出除了该数字本身的剩下的数字的乘积。

同时要求线性时间复杂度和O(1)空间复杂度。

我们试想,通过从左往右的一遍扫描,能否得到当前数字之前的所有数字的乘积?答案是肯定的!我们可以申请一个等大的数组,第一个记录对应第一个元素的前面数字乘积,很显然是1(因为当前数字不算,而之前又没有数字,只能是1);往后递推,第二个记录对应除第二个元素之前的所有数字乘积,即需要刚才的1乘以刚才的第一个数字;以此类推,核心思想就是通过新的数组记录之前所有数字的乘积,属于动态规划。

从左往右遍历完成之后,新数组中对应数字的结果是所有左侧数字的乘积;那再从右往左便利一遍,再记录对应数字右侧所有数字的乘积,最终把两个数乘起来,不就得到想要的结果了吗。

从右往左乘的过程,其实没有必要再申请一个新的数组了,只需要申请个别变量记录当前值,在刚才的数组上做即可。因为,当前值只跟上一个值有关。

通过一左一右两次扫描,就能够得到所求结果了。

代码

public int[] productExceptSelf(int[] nums) {        int[] rst = new int[nums.length];        rst[0] = 1;        for(int i=1;i<nums.length;i++){            rst[i] = rst[i-1]*nums[i-1];        }        int n = nums[nums.length-1];        for(int i=nums.length-2;i>=0;i--){            rst[i] = rst[i] * n;            n = n * nums[i];        }        return rst;    }
0 0
原创粉丝点击