【leetcode】Product of Array Except Self

原创 2015年11月19日 21:17:01

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

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        vector<int> result;
        int tmp = 1;
        result.push_back(tmp);
        for (vector<int>::const_iterator it = nums.begin(); it != nums.end() - 1; ++it)
        {
            tmp *= (*it);
            result.push_back(tmp);
        }
        tmp = 1;
        vector<int>::iterator it_result = result.end() - 2;
        for (vector<int>::const_iterator it = nums.end() - 1; it != nums.begin(); --it)
        {
            tmp *= (*it);
            (*it_result) *= tmp;
            --it_result;
        }
        
        return result;
    }
};


Personal Note:

遍历nums两次,第一次正序,计算索引i之前各数乘积并存入result,第二次反序,计算索引i之后各数乘积并与之前result相乘,得到最终result

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

leetcode笔记:Product of Array Except Self

该题的大意是,给定一个整数数组,让我们返回一个新数组,对于新数组中每一个位置上的数,是原始数组其他位置上的数的乘积。题目限定了时间复杂度:O(n),而且对空间复杂度也有要求。...

leetcode_Product of Array Except Self

1.改题目的要求返回一个数组,该数组的product[i]=num[0]*num[1]*.....num[i-1]*num[i+1]*...*num[num.length-1]; 2.由于要求出除i位...

Leetcode_238_Product of Array Except Self

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/48598939 Given an array of...

leetcode——Product of Array Except Self

题目Given an array of n integers where n > 1, nums, return an array output such that output[i] is equa...

《leetCode》:Product of Array Except Self

题目Given an array of n integers where n > 1, nums, return an array output such that output[i] is equ...

【leetCode】Product of Array Except Self

题目: Given an array of n integers where n > 1, nums, return an array output such that output[i] ...

LeetCode- 238. Product of Array Except Self

Problem: Given an array of n integers where n > 1, nums, return an array output such that outpu...

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 ...

<LeetCode OJ> 238. Product of Array Except Self

238. Product of Array Except Self My Submissions Question Total Accepted: 31438 Total Submission...

LeetCode笔记:238. Product of Array Except Self

计算除了该元素以外所有元素的乘积
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:【leetcode】Product of Array Except Self
举报原因:
原因补充:

(最多只允许输入30个字)