【发布时间】:2021-05-13 02:39:55
【问题描述】:
我有一个函数,它以 2 个 List 作为参数。我们想要的最终结果是检查 从第一个列表中,有多少元素小于等于第二个列表中的每个元素?
例如:
firstlist = [1,4,2,4]
secondList = [3,5]
输出 = [2,4]
说明:
secondList[3] >= firstList[1,2] 所以总数为 2。
secondList[5] >= firstList[1,4,2,4] 所以总数为 4。
我已经写了一个解决方案,但这不是优化的。
public List<Integer> counts(List<Integer> teamA, List<Integer> teamB) {
// Write your code here
int[] b = teamB.stream().mapToInt(i -> i).toArray();
int[] a = teamA.stream().mapToInt(i -> i).toArray();
int counter;
List<Integer> goals = new ArrayList<>();
for (int i= 0;i<b.length;i++){
counter= 0;
for (int j =0;j < a.length; j++){
if (a[j] <= b[i]){
counter++;
}
}
goals.add(counter);
}
return goals;
}
【问题讨论】:
-
它给出了正确的结果吗?如果不是,那是什么问题,如果确实如此,您想改进什么? (请注意,您可以直接在 teamA 和 teamB 上进行迭代,而不是仅仅为了它而创建数组)
-
这看起来像是一个学习练习,所以最好自己尝试一下。从 teamB 获取一个流并将每个元素映射到从 teamA 中少于它的元素的数量,然后收集回一个列表。
-
@assylias : 是的,上面是有效的,如果列表中的元素太多,则需要更长的时间,因为我们使用 for 循环并遍历每个元素
-
您接受的解决方案(使用流)也在幕后使用了一个循环 - 复杂性是相同的,流构造最多只能执行相同的操作。
标签: java optimization java-8