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

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

知道对撞指针,但是以为要每次都要重新乘。两边开始,对应2个循环。

[一句话思路]:

用res[i]来累乘,降低时间复杂度

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

用res[i]来累乘 指定数组中的每一个数,降低时间复杂度n

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

for (int i = 1; i < n; i++) {
            res[i] = res[i - 1] * nums[i - 1]; 
        }

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

class Solution {
    public int[] productExceptSelf(int[] nums) {
        //ini: n, res
        int n = nums.length, right = 1;
        int[] res = new int[n];
        res[0] = 1;
        
        //left to right
        for (int i = 1; i < n; i++) {
            res[i] = res[i - 1] * nums[i - 1]; 
        }
        
        //right to left
        for (int j = n - 1; j >= 0; j--) {
            res[j] *= right;
            right *= nums[j];
        }
        
        return res;
    }
}
View Code

 

posted @ 2018-05-05 17:12  苗妙苗  阅读(135)  评论(0编辑  收藏  举报