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;
        }
    };
  • 相关阅读:
    RHEL5.8使用yum安装xclock
    Linux下磁盘分区、挂载、卸载操作记录
    CentOS6.5磁盘分区和挂载操作记录
    CentOS环境下下调整home和根分区大小
    PowerDesigner连接Oracle数据库(32位)反向生成物理数据模型
    Create-React-App脚手架使用方法
    react 简书开发笔记
    本地连接服务器的mongodb
    使用mongoose连接mongodb(转载文章)
    将koa+vue部署到服务器
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/5030916.html
Copyright © 2011-2022 走看看