leetcode--Product of Array Except Self

来源:互联网 发布:php查找字符串位置 编辑:程序博客网 时间:2024/06/07 00:37

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


题意:给定一个数组,返回一个结果数组。要求结果数组中的每个元素,等于原数组中的该位置以外的元素的乘积。

例如{1,2,3,4},1位置上的,为2*3*4,那么结果数组的0位就是24

要求不能使用除法,并且时间复杂度为O(n)

你能在常数空间实现吗?output[]数组的空间不计算在内

分类:数组


解法1:解法有点巧妙。使用一个数组,保存元素组某位置,例如i,保存i前的所以元素的乘积

另外一个数组,保存i后所有元素的乘积

最后这两个数组相乘

[java] view plain copy
  1. public class Solution {  
  2.     public int[] productExceptSelf(int[] nums) {  
  3.         int len = nums.length;  
  4.         int[] output = new int[len];  
  5.         int[] helper = new int[len];  
  6.         output[0] = 1;  
  7.         helper[len-1] = 1;  
  8.         for(int i=1;i<len;i++){//计算i之前的乘积  
  9.             output[i] = nums[i-1]*output[i-1];  
  10.         }  
  11.         for(int i=len-2;i>=0;i--){//计算i之后的乘积  
  12.             helper[i] = nums[i+1]*helper[i+1];  
  13.         }  
  14.         for(int i=0;i<len;i++){  
  15.             output[i] = output[i]*helper[i];  
  16.         }  
  17.         return output;  
  18.     }  
  19. }  

优化一下代码:

[java] view plain copy
  1. public class Solution {  
  2.     public int[] productExceptSelf(int[] nums) {  
  3.         int len = nums.length;  
  4.         int[] output = new int[len];  
  5.         int[] helper = new int[len];  
  6.         output[0] = 1;  
  7.         helper[len-1] = 1;  
  8.         for(int i=1;i<len;i++){  
  9.             output[i] = nums[i-1]*output[i-1];//计算i之前的乘积  
  10.             helper[len-i-1] = nums[len-i]*helper[len-i];//计算i之后的乘积  
  11.         }  
  12.         for(int i=0;i<len;i++){  
  13.             output[i] = output[i]*helper[i];  
  14.         }  
  15.         return output;  
  16.     }  
  17. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/47906303