题目:
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; } }
测试:
238. Product of Array Except Self
原文:http://www.cnblogs.com/yrbbest/p/5003998.html