LeetCode 238 Product of Array Except Self (思维)

来源:互联网 发布:php 反转字符串 编辑:程序博客网 时间:2024/05/17 07:43

Given an array of n integers where n > 1, nums, return an arrayoutput such thatoutput[i] is equal to the product of all the elements ofnums exceptnums[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.)


题目链接:https://leetcode.com/problems/product-of-array-except-self/


题目分析:O(n)时间且不能用除法很容易想到记录前缀后缀积来计算枚举点的值

public class Solution {    public int[] productExceptSelf(int[] nums) {        int sz = nums.length;        int[] ans = new int[sz];        int[] pre = new int[sz];        int[] suf = new int[sz];        pre[0] = nums[0];        suf[sz - 1] = nums[sz - 1];        for (int i = 1; i < sz; i ++) {            pre[i] = nums[i] * pre[i - 1];        }        for (int i = sz - 2; i >= 0; i --) {            suf[i] = nums[i] * suf[i + 1];        }        ans[0] = suf[1];        ans[sz - 1] = pre[sz - 2];        for (int i = 1; i < sz - 1; i ++) {            ans[i] = pre[i - 1] * suf[i + 1];        }        return ans;    }}

Follow up中提到常数空间求解,仔细分析可以发现,ans[i]的值是由pre[i - 1] * suf[i + 1]得到的,而pre[i - 1]和sum[i + 1]则分别是从前往后和从后往前递推得到的,因此可以在递推的过程中直接计算左边和右边对i点的累乘值,这样就不用两个额外的数组记录前后缀了,直接计算左右累乘值的时候要先乘再更新,保证更新ans[i]的前后缀累乘积不包括nums[i],最后跑下来会发现运行时间变慢了,其实比上面O(n)空间的方法多了两个常数时间

public class Solution {    public int[] productExceptSelf(int[] nums) {        int sz = nums.length;        int[] ans = new int[sz];        Arrays.fill(ans, 1);        int left = 1, right = 1;        for (int i = 0; i < sz; i ++) {            ans[i] *= left;            left *= nums[i];            ans[sz - i - 1] *= right;            right *= nums[sz - i - 1];        }        return ans;    }}



0 0