zoukankan      html  css  js  c++  java
  • [LeetCode]102. 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.)

    Subscribe to see which companies asked this question

     
    解法1:不考虑常数空间复杂度,设置两个辅助数组,扫描两次数组,分别保存当前值左边所有数的乘积和右边所有数的乘积。最后再循坏一遍,将两个辅助数组对应位置相乘即为输出。
    class Solution {
    public:
        vector<int> productExceptSelf(vector<int>& nums) {
            int n = nums.size();
            vector<int> leftPro(n, 1), rightPro(n, 1), output(n, 0);
            for (int i = 1; i < n; ++i)
                leftPro[i] = leftPro[i - 1] * nums[i - 1];
            for (int i = n - 2; i >= 0; --i)
                rightPro[i] = rightPro[i + 1] * nums[i + 1];
            for (int i = 0; i < n; ++i)
                output[i] = leftPro[i] * rightPro[i];
            return output;
        }
    };

    解法2:要压缩空间复杂度至常数,而输出数组不计入在内,可以利用输出数组先保存leftPro或者rightPro中的一个,然后再扫描数组,将相应位置乘上rightPro/leftPro即可。

    class Solution {
    public:
        vector<int> productExceptSelf(vector<int>& nums) {
            int n = nums.size(), rightPro = 1;
            vector<int> output(n, 1);
            for (int i = 1; i < n; ++i)
                output[i] = output[i - 1] * nums[i - 1];
            for (int i = n - 2; i >= 0; --i) {        
                rightPro *= nums[i + 1];
                output[i] *= rightPro;
            }
            return output;
        }
    };
  • 相关阅读:
    #线段树,矩阵乘法#LOJ 3264「ROIR 2020 Day 2」海报
    #线段树#洛谷 4428 [BJOI2018]二进制
    #Trie#洛谷 7717 「EZEC-10」序列
    shell脚本生成双色球号码
    k8s的tomcat多pod session会话保持配置
    国产系统优麒麟系统使用
    grdi报错--grid的asm磁盘丢失处理方法
    centos7上安装oracle的sqlplus客户端
    linux挂载
    linux占用100%cpu的java处理
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/5030916.html
Copyright © 2011-2022 走看看