【问题标题】:Finding minimum integer in ArrayList without collections在没有集合的 ArrayList 中查找最小整数
【发布时间】:2015-04-09 18:49:48
【问题描述】:

我试图通过使用两个简单的for 循环来找到ArrayList 中的最小整数。我最初尝试使用一个for 循环,但它没有正确更新。我还没有学过collections,所以应该不用collections代码来完成。

这就是我所拥有的:

public static void printInOrder(ArrayList<Integer> data){

 int minIndex = 0 ;
 for(int i = 0; i < data.size(); i++){
   minIndex = i;
   for(int j = i + 1; j < data.size() - 1; j++){
     if(data.get(j) < data.get(minIndex)){
       minIndex = j;}

   }
   System.out.println(data.get(minIndex) + " ");
 }
}//printInOrder

我的最小值似乎总是列表中的最后一个值,所以我尝试在第一个 for 循环中打印 data.get(minIndex) 以查看发生了什么,它似乎更新了不同的值,最后,最后一个值。我不知道为什么会这样。

这是它正在打印的示例:

Original list: [47, 19, 46, 42, 15, 26, 36, 27, 13, 15, 1, 40, 34, 14, 6, 34, 28, 12, 15, 13] Print the minimum: 1 1 1 1 1 1 1 1 1 1 1 6 6 6 6 12 12 12 15 13

【问题讨论】:

  • 你不需要双循环。只要你保持当前的最小值,单循环就应该这样做
  • 对arraylist排序并返回索引为0的元素?
  • @gtgaxiola,如果我用一个循环尝试它,我会在我的if 语句中比较什么?因为我尝试了一段时间,但它也没有给我正确的最小值。
  • 你保留一个临时变量来存储当前最小值。
  • 对于所有起始索引i,您的代码当前成功地找到了从i 开始的列表中的最小编号。您只想找到从 0 开始的列表中最小的数字。

标签: java arraylist


【解决方案1】:

如果您想避免使用集合,可以使用此快速解决方案。

public static void printInOrder(ArrayList<Integer> data){

    Integer[] array = (Integer[]) data.toArray();
    Arrays.sort(array);
    System.out.println(array[0]);

}

在这种情况下,最小的整数总是在索引 0 处。

或者,如果您确实想使用循环遍历整个 ArrayList,我建议您将实际值存储在变量而不是索引中。这样做,你会得到:

public static void printInOrder(ArrayList<Integer> data){

    int minInteger = data.get(0);
    for(int i = 1; i < data.size(); i++){
        if(data.get(i) < minInteger) minInteger= data.get(i);
    }
    System.out.println(minInteger);

}

【讨论】:

  • Integer[] array = data.toArray(); 无法编译。
  • 我的错,忘记投了。 :)
【解决方案2】:

你不应该通过排序来找到最小值

这是代码

public static void Min(int arr[])
{
   int min = arr[0];
    int i=0;
while(i<arr.length)
 {
        if (arr[i] < min) {
            min=arr[i];
        }
    }
    return min;
}

【讨论】:

  • 好吧,如果您对排序感兴趣,然后找到最小值没问题,但问题是它没有意义,我认为它需要双倍的时间才能找到一个最小值最小算法
  • 通过分析,线性搜索的复杂度为 O(n),最坏的情况下有 n 次迭代。使用 Java 的内置排序功能,它以 O(n log n) 运行,之后获得最小值肯定是 O(1)。这样,我认为它并没有看起来那么低效。
  • @theguywhodreams 这是一种看待它的方式,另一种是 log2(1024) 已经达到 10,因此对 1024 个元素进行排序以找到最小值的复杂度大约是线性搜索的 10 倍.这是否被认为是有效(足够)与否高度依赖于实际用例。
【解决方案3】:

未经测试:

public static int calculateMinIndex(final ArrayList<Integer> data) {
    int minIndex = 0;
    for(int i = 0; i < data.size() - 1; i++) {
        if(data.get(i) > data.get(i+1)) {
            minIndex = i+1;
        }
    }
    return minIndex;
}

【讨论】:

    猜你喜欢
    • 2015-07-21
    • 1970-01-01
    • 2012-12-29
    • 2014-01-02
    • 1970-01-01
    • 2016-01-09
    • 2011-05-15
    • 2020-08-16
    • 2011-04-19
    相关资源
    最近更新 更多