238. 除自身以外数组的乘积 C++

给你一个整数数组 nums,返回 数组 answer ,其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。

题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在  32 位 整数范围内。

请不要使用除法,且在 O(n) 时间复杂度内完成此题。

示例 1:

输入: nums = [1,2,3,4]
输出: [24,12,8,6]
示例 2:

输入: nums = [-1,1,0,-3,3]
输出: [0,0,9,0,0]

提示:

2 <= nums.length <= 105
-30 <= nums[i] <= 30
保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在  32 位 整数范围内

ans1. 

用除法,不和题意,且效率很低

执行用时:28 ms, 在所有 C++ 提交中击败了21.56%的用户

内存消耗:24.3 MB, 在所有 C++ 提交中击败了45.20%的用户

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int cnt_0 = 0;
        int idex_0 = -1;
        int n = nums.size();
        vector<int> answer;
        for(int i = 0;i < n;i++){
            answer.push_back(0);
        }

        for(int i = 0;i < n;i++){
            if(nums[i] == 0) {
                cnt_0++;
                if(idex_0 == -1) idex_0 = i;
                // 记录第一个0下标
            }
        }
        if(cnt_0 > 1) return answer;
        // 超过一个0,则积全0

        long long sum = 1;
        for(int j = 0;j < idex_0;++j){
            sum *= nums[j];
        }
        for(int j = idex_0+1;j < n;j++){
            sum *= nums[j];
        }

        if(cnt_0 == 1){
            answer[idex_0] = sum;
            return answer;
        }

        for(int i = 0;i < n;i++){
            answer[i] = sum/nums[i];
        }
        return answer;

    }
};

ans2.

用两个辅助数组分别存每位的左右乘积

执行用时:16 ms, 在所有 C++ 提交中击败了92.76%的用户

内存消耗:25.6 MB, 在所有 C++ 提交中击败了5.04%的用户

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int n = nums.size();
        vector<int> Left(n);
        vector<int> Right(n);
        Left[0] = 1;
        Right[n-1] = 1;
        // 分别表示下标i元素左边、右边的乘积

        for(int i = 1;i < n;i++){
            Left[i] = Left[i-1] * nums[i-1];
        }
        for(int j = n -2;j >= 0;j--){
            Right[j] = Right[j+1] * nums[j+1];
        }

        vector<int> answer;
        for(int i = 0;i < n;i++){
            answer.push_back(Left[i]*Right[i]);
        }

        return answer;
    }
};

ans3.

直接在输出数组上操作,按题意空间复杂度降为O(n)

执行用时:16 ms, 在所有 C++ 提交中击败了92.76%的用户

内存消耗:23.4 MB, 在所有 C++ 提交中击败了82.28%的用户

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int n = nums.size();
        vector<int> answer(n);

        // 先求出left积
        answer[0] = 1;
        for(int i = 1;i < n;i++) answer[i] = answer[i-1] * nums[i-1];

        // 求right积 并乘left填回answer
        int curr = 1;
        for(int j = n-2;j >= 0;j--) {
            curr *= nums[j+1];
            answer[j] = answer[j] * curr;
        }

        return answer;
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值