前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 0238 - Product of Array Except Self

LeetCode 0238 - Product of Array Except Self

作者头像
Reck Zhang
发布2021-08-11 12:00:20
1270
发布2021-08-11 12:00:20
举报
文章被收录于专栏:Reck ZhangReck Zhang

Product of Array Except Self

Desicription

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:

代码语言:javascript
复制
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.)

Solution

代码语言:javascript
复制
class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        vector<int> pre(nums.size(), 1);
        vector<int> suf(nums.size(), 1);
        vector<int> res(nums.size(), 1);
        
        for(int i = 0; i < nums.size(); i++) {
            pre[i] = i ? pre[i - 1] * nums[i] : nums[i];
        }
        for(int i = nums.size() - 1; i > 0; i--) {
            suf[i] = i == nums.size() - 1 ? nums[i] : suf[i + 1] * nums[i];
        }
        for(int i = 0; i < nums.size(); i++) {
            if(i == 0) {
                res[i] = suf[i + 1];
            } else if(i == nums.size() - 1) {
                res[i] = pre[i - 1];
            } else {
                res[i] = pre[i - 1] * suf[i + 1];
            }
        }
        return res;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-09-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Product of Array Except Self
    • Desicription
      • Solution
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档