首页 > 代码库 > 238. Product of Array Except Self

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/

7/25/2017

3ms, 10%

本来的想法是用2个数组分别从前往后和从后往前乘,最后2数组相应元素互相乘。space complexity O(n)。

下面的方法用tmp代替了第二个数组

 1 public class Solution {
 2     public int[] productExceptSelf(int[] nums) {
 3         int[] result = new int[nums.length];
 4 
 5         result[0] = 1;
 6         for (int i = 1; i < nums.length; i++) {
 7             result[i] = result[i - 1] * nums[i - 1];
 8         }
 9         int tmp = 1;
10         for (int i = nums.length - 2; i >= 0; i--) {
11             tmp *= nums[i + 1];
12             result[i] *= tmp;
13         }
14         return result;
15     }
16 }

参考

http://www.cnblogs.com/yrbbest/p/5003998.html

更多讨论

https://discuss.leetcode.com/category/294/product-of-array-except-self

 

238. Product of Array Except Self