238. Product of Array Except Self

来源:互联网 发布:知党规 行敬畏 编辑:程序博客网 时间:2024/04/30 08:38

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
原创粉丝点击