我想比较两个列表(eastList和westList)。 EastList
将包含值0
,westList
将包含值1
。返回值应为5
。代码是正确的。我可以用流写第二个for循环吗?如何编写使用Java 8功能摘录的代码以获得高效代码?请帮忙。谢谢...
import java.util.*;
public class Solution {
public int solution(int[] A) {
List<Integer> eastList = new ArrayList<>();
List<Integer> westList = new ArrayList<>();
int count = 0;
for(int i = 0; i < A.length; i++) {
if(A[i] == 0) {
eastList.add(i);
}
else {
westList.add(i);
}
}
for(int m = 0; m < eastList.size(); m++) {
for(int n = 0; n < westList.size(); n++) {
if(eastList.get(m) < westList.get(n)) {
count++;
}
}
}
return count;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] A = {0,1,0,1,1};
solution.solution(A);
}
}
对于Java9及更高版本,您可以使用dropWhile
eastList.stream().map(
east -> westList.stream().dropWhile(west -> west <= east).count()
).sum()
而且(在我看来)基于流的代码更具表现力,因为dropWhile
和count
调用准确地描述了我们对east
和westList
的处理方式>
更新:根据拉胡尔的评论进行修正