java - 比较/排序元素,然后使用具有 O(n) 复杂度的数组列表对它们进行平方
问题描述
我有一个嵌套循环,它遍历列表中的每个元素,对其进行比较/排序,然后我试图对列表中的数字求平方(记住它们需要排序)。问题是当我运行我的程序时,我使用的“测试”数组列表不会打印最后一个平方,但它会打印倒数第二个平方两次。例如,如果我的数组列表是 (1,2,3,4,5),我的代码应该打印 (1,4,9,16,25) 但它会打印 (1,4,9,16,16)。我似乎无法弄清楚为什么。
我的代码:
public static void sortSquares(List<Integer> tempList) {
int result = 0;
for (int i = 0; i < tempList.size(); i++) {
for (int j = tempList.size() - 1; j > i; j--){
if (tempList.get(i) > tempList.get(j)) {
result = tempList.get(j) * tempList.get(j);
}
else if (tempList.get(j) > tempList.get(i)) {
result = (tempList.get(i) * tempList.get(i));
}
}
System.out.println(result);
}
}
解决方案
在最后一个外部循环 wheni = 4
中,内部循环变为:
for (int j = 4; j > 4; j--)
它什么都不做,外部循环打印result
,其中包含前一个值 (16)。
解决方案可能是将内部循环的条件替换为j >= i
. 您还需要替换 的条件if
,因为tempList.get(j)
现在等于tempList.get(i)
:
for (int i = 0; i < tempList.size(); i++) {
for (int j = tempList.size() - 1; j >= i; j--){
if (tempList.get(i) > tempList.get(j)) {
result = tempList.get(j) * tempList.get(j);
}
else if (tempList.get(j) >= tempList.get(i)) {
result = (tempList.get(i) * tempList.get(i));
}
}
System.out.println(result);
}
它适用于(1,2,3,4,5)。
话虽如此,使用更简单的代码可以获得相同的结果:
Collections.sort(tempList); /* Optional, if you want to sort the result */
List<Integer> result = new ArrayList<>();
for (int i = 0; i < tempList.size(); i++) {
result.add(tempList.get(i) * tempList.get(i));
}
System.out.println(result);
推荐阅读
- haproxy - iptables 没有将任何流量转发到 HAProxy
- javascript - 根据另一个数组的值对数组进行排序
- java - Spring Web框架中是否有任何特定的验证机制
- android - 所有 gms/firebase 库必须使用完全相同的版本(混合版本会导致运行时崩溃)。找到版本 16.1.1 16.0.1 16.0.0 15.0.1
- sql - SQL 数据提取和日期差异
- sql - 具有 2 个表的递归 CTE 在 Oracle / SQL 中不起作用
- javascript - Javascript/Moment.js 为今天、晚上 10:00 等生成 Unix 时间戳
- c# - C# & SQL Server:查询需要很长时间
- mongodb - 如何从 Mongodb 中的两个不同集合中合并?
- arrays - 将 n 名球员分成大小为 k 且实力相同(或差异最小)的两支球队