238. Product of Array Except Self

題目:html

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

For example, given [1,2,3,4], return [24,12,8,6].code

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

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

7/25/2017element

3ms, 10%leetcode

原本的想法是用2個數組分別從前日後和從後往前乘,最後2數組相應元素互相乘。space complexity O(n)。get

下面的方法用tmp代替了第二個數組it

 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

相關文章
相關標籤/搜索