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

tip:不能用除法、时间复杂度要求O(n)(这样遍历数组的方法也不行了)

想了好久都没想到O(n)的方法,最后还是用了除法,在有0的情况下还有另外处理,比较复杂,代码如下,仅供忽略

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] results = new int[nums.length];
        int product = 1;
        int zeroPos = 0;
        for(int i = 0;i<nums.length;i++) {
            product *= nums[i];
            if(nums[i] == 0) {
                zeroPos = i;
            }
        }
        if(product == 0) {
            for(int i = 0;i<results.length;i++) {
                results[i] = 0;
            }
            product = 1;
            for(int i = 0;i<nums.length;i++) {
                if(i == zeroPos) {
                    continue;
                }
                product *= nums[i];
            }
            results[zeroPos] = product;
        } else {
            for(int i = 0;i<nums.length;i++) {
                results[i] = product/nums[i];
            }
        }
        return results;
    }
}

正确解法

思路:result[i]的一种求法是:可以先依次乘i的右边各个元素,再乘i的左边各个元素

如题目中的[1,2,3,4],result[1] = 3 * 4 * 1 = 12

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int result[] = new int[n];
        result[n-1] = 1;
        for(int i = n-2;i>=0;i--) {
            result[i] = result[i+1] * nums[i+1];
        }
        int left = 1;
        for(int i = 0;i<n;i++) {
            result[i] = result[i] * left;
            left = left * nums[i];
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值