Given an array of numbers, nums, return an array of
numbers products, where products[i] is the product of
all nums[j], j != i.
Input : [1, 2, 3, 4, 5]
Output: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5),
(1*2*3*4)]
= [120, 60, 40, 30, 24]
您必须使用除法在O(N)中执行此操作。
答案 0 :(得分:0)
这样做:
int[] arr = new int[] {1, 2, 3, 4, 5};
int[] outPut = new int[arr.length];
for(int i=0;i<arr.length;i++){
int res=Arrays.stream(arr).reduce(1, (a, b) -> a * b);
outPut[i] = res/arr[i];
}
System.out.println(Arrays.toString(outPut));
答案 1 :(得分:0)
int[] arr = {1, 2, 3, 4, 5};
int[] output = new int[arr.length];
int product = 1;
for (int i = 0; i < arr.length; i++)
product *= arr[i];
for (int i = 0; i < arr.length; i++) {
output[i] = product / arr[i];
System.out.println(output[i]);
}
总时间复杂度为O(n)。
这是我对此进行测试的链接:http://ideone.com/dDVwrO
步骤:
i
,将(1)中获得的乘积除以arr[i]
,然后将结果放入输出数组。