zoukankan      html  css  js  c++  java
  • 238. Product of Array Except Self

    问题描述:

    Given an array nums of n integers where n > 1,  return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

    Example:

    Input:  [1,2,3,4]
    Output: [24,12,8,6]
    

    Note: Please solve it without division and in O(n).

    Follow up:
    Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

    解题思路:

    求数组其他元素的乘积。

    我们可以从左向右乘一遍,不乘本身,从i = 1 开始乘,得到一个数组leftProduct。

    再从右向左乘一遍,不乘本身,从i=nums.size()-2,得到数组rightProduct。

    然后将Left和Right相乘得到最后结果。

    这里我扩出去了几位用于对齐。

    代码:

    class Solution {
    public:
        vector<int> productExceptSelf(vector<int>& nums) {
            vector<int> ret;
            if(nums.empty()) return ret;
            vector<int> leftProduct(nums.size()+1, 1);
            vector<int> rightProduct(nums.size()+1, 1);
            
            for(int i = 1; i <= nums.size(); i++){
                leftProduct[i]  = leftProduct[i-1]*nums[i-1];
            }
            for(int i = nums.size()-1; i > -1; i--){
                rightProduct[i] = rightProduct[i+1]*nums[i];
            }
            
            for(int i = 0; i < nums.size(); i++){
                ret.push_back(leftProduct[i] * rightProduct[i+1]);
            }
            return ret;
        }
    };

    Follow Up:

    使用一个变量来记录单向乘积

    class Solution {
    public:
        vector<int> productExceptSelf(vector<int>& nums) {
            if(nums.size() == 0){
                return vector<int>();
            }
            vector<int> ret(nums.size(), 1);
            //from left to right
            for(int i = 1; i < nums.size(); i++){
                ret[i] = ret[i-1] * nums[i-1];
            }
            //fron right to left
            int rightSide = 1;
            for(int i = nums.size() - 2; i > -1; i--){
                rightSide *= nums[i+1];
                ret[i] *= rightSide;
            }
            
            return ret;
        }
    };
  • 相关阅读:
    ES5 05 Function扩展
    ES5 04 Array扩展
    ES5 03 Object扩展
    ES5 02 JSON对象
    ES5 01 严格模式
    Oracle 数据库复制
    PB函数大全
    Handle( ) //得到PB窗口型对象的句柄
    PB赋值粘贴 多个DW进行update
    pb 11 数据窗口空白,预览pb崩溃解决方案
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/11589599.html
Copyright © 2011-2022 走看看