你的位置:首页 > Java教程

[Java教程]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].

代码如下:

 1 public class Solution { 2   public int[] productExceptSelf(int[] nums) { 3     int[] output=new int[nums.length]; 4     List<Integer> list=new ArrayList<>(); 5     int sum=1; 6     for(int i=0;i<nums.length;i++) 7     { 8       if(nums[i]!=0) 9       sum=sum*nums[i];10       else list.add(i);11     }12     13     if(list.size()==1)14     {15       output[list.get(0)]=sum;16       return output;17     }18     else if(list.size()>1)19       return output;20       21     for(int i=0;i<nums.length;i++)22     output[i]=sum/nums[i];23     24     return output;25     26     27   }28 }