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;
        }
    };
  • 相关阅读:
    CentOS安装thrift
    6个用于大数据分析的最好工具
    我的助理辞职了!——给不听话的下属看看
    用Redis bitmap统计活跃用户、留存
    Java从入门到精通——数据库篇Oracle 11g服务详解
    Java从入门到精通——数据库篇之OJDBC版本区别
    非常有用!eclipse与myeclipse恢复已删除的文件和代码
    Redis 代理服务Twemproxy
    Redis集群明细文档
    正则表达式
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/5030916.html
Copyright © 2011-2022 走看看