【发布时间】:2017-10-29 17:26:02
【问题描述】:
这是一个简单的算法问题,
给定一个n>1的整数数组,nums,返回一个数组输出 使得 output[i] 等于所有元素的乘积 除 nums[i] 之外的 nums。在 O(n) 中解决它而不用除法。为了 例如,给定 [1,2,3,4],返回 [24,12,8,6]。
这是我的解决方案,
public static int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
int leftProduct = 1;
int rightProduct = 1;
for(int i = 0; i < result.length; i++){
result[i] = leftProduct;
leftProduct *= nums[i];
}
for(int i=nums.length -1; i >= 0; i --){
result[i] *= rightProduct;
rightProduct *= nums[i];
}
return result;
}
public static void main(String[] args) {
int[] output = productExceptSelf(new int[]{1, 2, 3, 4});
Arrays.stream(output).forEach(System.out::println);
}
这很好用。我想要学习的是如何在 Java 8 中重写这段代码。就像 Java 8 中循环的不同选项一样。
【问题讨论】:
-
以上代码在 Java 8 中完全有效。
-
@JoeC 我有点知道,我的意思是如何使用 Java 8 函数构造重写代码。
-
老实说,这个特殊的例子是我不会尝试这样做的。这主要是因为您在循环中操作多个变量,而
StreamAPI 的设计不是很好。 -
流不太适合(就像现在一样)让临时结果流入进一步的流,恕我直言 - 对每个人来说都是一种不幸的浪费时间。。提示:
System.out.println(Arrays.toString(output));更好看。
标签: arrays java-8 java-stream