[LeetCode]238.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.)

思路

这里写图片描述

对于i = 5 时 result[5] = (nums[0] * nums[1] * nums[2] * nums[3] * nums[4] ) * (nums[6] nums[7] * nums[8] * nums[9] * nums[10])

从上面开始看出对于第i个,我们只要知道它左边的连续乘积它右边的连续乘积 就OK了。

代码

/*---------------------------------------
*   日期:2015-07-31
*   作者:SJF0115
*   题目: 238.Product of Array Except Self
*   网址:https://leetcode.com/problems/product-of-array-except-self/
*   结果:AC
*   来源:LeetCode
*   博客:
-----------------------------------------*/
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int size = nums.size();
        vector<int> result(size,0);
        vector<int> left(size,0);
        vector<int> right(size,0);
        int leftNum = 1,rightNum = 1;
        // left[i] 为 nums[0]...nums[i-1]的连续乘积
        // right[i] 为 nums[i+1]...nums[size-1]的连续乘积
        for(int i = 0;i < size;++i){
            left[i] = leftNum;
            right[size-i-1] = rightNum;
            leftNum *= nums[i];
            rightNum *= nums[size-i-1];
        }//for
        // 计算不包括自己的所有乘积
        for(int i = 0;i < size;++i){
            result[i] = left[i] * right[i];
        }//for
        return result;
    }
};

int main(){
    Solution s;
    vector<int> vec = {1,2};
    vector<int> result = s.productExceptSelf(vec);
    int size = result.size();
    for(int i = 0;i < size;++i){
        cout<<result[i]<<" ";
    }//for
    return 0;
}

运行时间

这里写图片描述

<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>
展开阅读全文

没有更多推荐了,返回首页