码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 238. Product of Array Except Self

时间:2018-10-14 13:48:59      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:bsp   you   解决   数组   count   lease   计算   style   记录   

Given an array nums of n integers where n > 1,  return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

Note: Please solve it without division and in O(n).

Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

题意:给一数组,输出除了这个数字以外所有数字的乘积

注意,不用除法(其实你用了它也不会报错),尽可能在常数级的空间内解决问题。

如果用除法大家肯定都会,不用除法,而且要在O(n)的条件下完成。

我们会到问题,关键有两点,数组和乘积,这个位置的答案可以看作是它左边所有数字的积乘以它右边数字的积

那么我们就需要额外开两个数组,分别从左向右 从右向左乘一次,最后在乘一次即可

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

 哈哈,这不满足常数空间的要求(也可以说就是O(1)空间的要求)

不能额外开空间,所以我们优化一下,一边计算一边记录

从右向左的,我们保存到res里,从左向右的,我们用一个int代替就行了(这样不会影响res中没有用的元素)

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] res = new int[nums.length];
        res[nums.length - 1] = nums[nums.length - 1];

        for (int i = nums.length - 2; i >= 0; i--) {
            res[i] = res[i + 1] *nums[i];
        }
        res[0] = res[1];
        int mix = nums[0];
        for (int i = 1; i < nums.length - 1; i++) {
            res[i] = mix * res[i + 1];
            mix *= nums[i];
        }
        res[nums.length - 1] = mix;
        return res;
    }
}

 

[LeetCode] 238. Product of Array Except Self

标签:bsp   you   解决   数组   count   lease   计算   style   记录   

原文地址:https://www.cnblogs.com/Moriarty-cx/p/9785609.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!