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

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

链接:  http://leetcode.com/problems/product-of-array-except-self/

题解:

求数组除了自己之外其他元素的乘积。 跟Trapping Rain Water很像,左右各自遍历一遍然后就可以得到结果了。

Time Complexity - O(n), Space Complexity - O(n)。

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        if(nums == null || nums.length == 0)
            return new int[]{};
        int len = nums.length;
        int[] res = new int[len];
        res[len - 1] = 1;
        
        for(int i = len - 2; i >= 0; i--)       // {a, b, c, d, e}  ->  {bcde, cde, de, 1}
            res[i] = res[i + 1] * nums[i + 1];
        
        int lo = nums[0];
        
        for(int i = 1; i < len; i++) {         // {bcde, cde, de, 1} -> {bcde, acde, abde, abcd}
            res[i] *= lo;
            lo *= nums[i];
        }
        
        return res;    
    }
}

二刷:

这道题在Amazon店面的时候直接考到了。Follow up是什么样的输入这样写会不对,哪里会overflow。再follow up是假如我有两个很长的nums,不能放进内存怎么办。其实利用乘法的交换律和结合律我们可以对其进行parallel。

下面写法是考虑可以放入内存,并且没有overflow。

  1. 我们先设一个结果数组output,初始化output[0] = 1。
  2. 然后从1到数组尾部进行遍历,动态规划,每次output[i] = output[i - 1] * nums[i - 1]
  3. 接下来设置一个变量product = 1, 用同样方法从 len - 2到数组头部进行遍历, product *= nums[i + 1], output[i] *= product
  4. 最后返回output

Java:

Time Complexity - O(n), Space Complexity - O(1)。 假如结果数组也算的话那Space Complexity就是O(n)。

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        if (nums == null || nums.length < 2) {
            return nums;
        }
        int len = nums.length;
        int[] output = new int[len];
        output[0] = 1;
        for (int i = 1; i < len; i++) {
            output[i] = output[i - 1] * nums[i - 1];
        }
        int product = 1;
        for (int i = len - 2; i >= 0; i--) {
            product *= nums[i + 1];
            output[i] *= product;
        }
        return output;
    }
}

测试:

原文地址:https://www.cnblogs.com/yrbbest/p/5003998.html