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

Array - 238. Product of Array Except Self

作者头像
ppxai
发布2020-09-23 17:06:53
3230
发布2020-09-23 17:06:53
举报
文章被收录于专栏:皮皮星球皮皮星球

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

思路:

当前位置的左边全部相乘,右边全部相乘,然后全乘起来就可以。乘右边的时候可以倒着计算就可以两边循环就得出结果。

代码:

java:

代码语言:javascript
复制
class Solution {

    public int[] productExceptSelf(int[] nums) {
        int len = nums.length;
        int[] res = new int[len];
        res[0] = 1;
        // left multi
        for (int i = 1; i < len; i++) {
            res[i] = res[i-1] * nums[i-1];
        }
            
        // right multi
        int right = 1;
        for (int i = len  -1; i >= 0; i--) {
            res[i] *= right;
            right *= nums[i];
        }
        
        return res;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年06月24日,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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