关闭

【leetcode】Product of Array Except Self

145人阅读 评论(0) 收藏 举报
分类:

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

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:5376次
    • 积分:246
    • 等级:
    • 排名:千里之外
    • 原创:20篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类