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

题意:

给定一个大小为n的数组,返回的结果数组为除了该元素之外的数组所有元素之积。


思路一:

暴力轮训。超时!


思路二:

维持两个数组,分别保存缺少对应元素之后的其他元素值,之后直接将两个数组相乘即为结果值。

例:

  • [1,a1,a1*a2,a1*a2*a3]
  • [a2*a3*a4,a3*a4,a4,1]
  • 代码:64ms
    class Solution {
    public:
        vector<int> productExceptSelf(vector<int>& nums) {
            
            int m = nums.size();
            vector<int> left(m);
            vector<int> right(m);
            
            left[0] = right[m-1] = 1;
            for(int i=1; i<m; i++){  
                left[i] = left[i-1] * nums[i-1];
            }
            
            for(int i=m-2; i>=0; i--){ 
                right[i] = right[i+1] * nums[i+1];
            }
            
            for(int i=0; i<m; i++){ 
                nums[i] = left[i] * right[i];
            }
            
            
            return nums;
        }
    };
    
    思路三:

    用两个常数替代两个数组,一个从前往后,一个从后往前,因为要做累乘,所以都从第一个元素开始,循环m次。即前元素从头到尾,后元素从尾到头,实现思路二类似的两个数组值重叠相乘。

    代码:60ms

    class Solution {
    public:
        vector<int> productExceptSelf(vector<int>& nums) {
            
            int m = nums.size();
            int left = 1;
            int right = 1;
            vector<int> result(m, 1);
            
            for(int i=0; i<m; i++){  //数组轮训一遍
                result[i] *= left;  //从数组头到数组尾
                left *= nums[i];
                result[m-1-i] *= right;  //数组尾到数组头
                right *= nums[m-1-i];
            }
            
            return result;
        }
    };
    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值