java - 从第一个列表中查找最小元素
问题描述
我有一个函数,它以 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;
}
解决方案
如果你想降低时间复杂度,那么你可以对第一个列表进行排序,然后对第二个列表中的每个元素应用二分搜索来查找更少的数字。
这样,时间复杂度将从 降低O(N*M)
到O(Mlog(N))
推荐阅读
- git - 如何进行合并提交
- sql - 如何在 2 分钟内将 90 亿条记录插入数据库?
- camunda - Camunda:提交响应后无法创建会话
- python - 在 Python 中使用迭代器创建无限随机游走
- postgresql - 在 postgres 的流复制中排除表的解决方法
- sql - 在 oracle 中,我可以将字符串放在 num 数据类型列中吗?
- python-3.x - 如何将经过验证的条目值绑定到变量?
- react-native - 在 Vue Native 中为 BottomTabNavigator 添加标题按钮和标题
- node.js - 在 Express JS 中使用 res.download 成功下载文件后如何使用 res.redirect?
- asp.net - 如何将数组类型对象作为空字符串数组而不是 NULL 传递?