首页 > 解决方案 > 比较/排序元素,然后使用具有 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);
        }
    }

标签: java

解决方案


在最后一个外部循环 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);

推荐阅读