leetcode刷题,总结,记录,备忘238

leetcode238

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

这题有点惭愧,, 自己没想出来,看了别人的解法,,顿时感觉简单,先从头遍历,将每一个位置上的之前的元素乘积保存在临时的数组中,然后再重尾巴开始倒着遍历数组再承一遍,将每个位置上右边的元素乘积与临时数组中的值相乘得到最终结果。自己在纸上写写画画走走流程就明白了。

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        vector<int>temp(nums.size(), 1);
        
        for (int i = 1; i < nums.size(); ++i)
        {
            temp[i] = temp[i-1] * nums[i-1];
        }
        int n = 1;
        for (int i = nums.size()-1; i >= 0; --i)
        {
            temp[i] *= n;
            n *= nums[i];
        }
        
        return temp;
        
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值