Product of Array Except Self

题目

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

Input:

  • 数组 :: int[]

Output:

  • 每一位存除这个数以外其他数的乘积 :: int[]

Intuition:

用constant的space,还有比这更露骨的提示嘛?除了two pointers 还能想到啥。左边的指针扫一遍,把每个数左边的乘积搞定,右边指针右边扫一遍,把右边的乘积搞定就OK了。

但素,我居然还是卡住了,数学不好的同学们,还是要写几个case确定你的关系式是正确的,两边的margin要处理正确。

public int[] productExceptSelf(int[] nums) {
        int[] res = new int[nums.length];
        int len = nums.length;
        int left = nums[0];
        res[0] = 1;
        //find product on the left side
        for (int i = 1; i < len; i++){
            res[i] = left;
            left *= nums[i];
        }
        
         //find product on the right side and multipy it with left side product
        int right = nums[nums.length - 1];
        for (int i = len - 2; i >= 0; i--){
            res[i] *= right;
            right *= nums[i];
        }
        return res;
    }

Reference

https://leetcode.com/problems/product-of-array-except-self/description/

    原文作者:石榴蒂凡尼_21e4
    原文地址: https://www.jianshu.com/p/1f9ed3d6e53e
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞