查找数组中最小值和最大值的有效方法

Efficient way for finding the min and max value in an array

我想找出整数数组中的最小值和最大值。

以下哪种方式效率更高?

  1. 对数组进行排序,然后查看开始和结束以获得最小值和最大值。

  2. 使用Arrays.asList()将数组转换为列表,然后使用Collections.min()方法。

我想使用它的代码如下:

// Find missing number from an array of consecutive numbers arranged randomly
import java.util.Arrays;

public class MissingNumber {

    public static void main(String[] args) {

        int[] consecutiveRandomNos = { 3, 6, 5 };

        System.out.println(addNumbers(consecutiveRandomNos));
        System.out.println("The missing number is "
                        + (returnSum(consecutiveRandomNos) - addNumbers(consecutiveRandomNos)));
    }

    public static int addNumbers(int... numbers) {
        int result = 0;

        for (int number : numbers) {
            result += number;
        }

        return result;
    }

    public static int returnSum(int... nos) {

        Arrays.sort(nos);

        int max = nos[nos.length - 1];

        int min = nos[0];

        int total = 0;

        for (int i = min; i <= max; i++) {
            total += i;
        }

        return total;
    }
}

Collection#min源代码:

585     public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
586         Iterator<? extends T> i = coll.iterator();
587         T candidate = i.next();
588 
589         while (i.hasNext()) {
590             T next = i.next();
591             if (next.compareTo(candidate) < 0)
592                 candidate = next;
593         }
594         return candidate;
595     }

时间复杂度为O(n)。如果您的排序算法是 O(n)(请post),它们在时间复杂度方面是相同的。

排序成本为 O(NlogN),通过数组查找最小和最大成本为 O(N)。 无需转换为列表,只需迭代数组即可。

排序最多为 O(Nlog(N))。 您可以在 O(n) 中简单地找到最小值和最大值,只需遍历数组即可。

int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for(int i=0; i<array.length; i++)
{
    if(array[i] < min)
       min = array[i]
    if(array[i] > max)
       max = array[i]
}

编辑:


我注意到您粘贴了一些额外的代码,并且您实际上想要在连续数字数组中查找缺失的数字。与其迭代那么多,还有 mathematical summations 可以在 O(1) 中为您提供帮助。事实上,你可以用一个 for 循环解决整个问题:

int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int sum = 0;
for(int i=0; i<array.length; i++)
{
    if(array[i] < min)
       min = array[i];
    if(array[i] > max)
       max = array[i];
    sum += array[i];
}

return (max - min + 1)(max + min)/2 - sum;