我想找出整数数组中的最小值和最大值。
以下哪种方式效率更高?
对数组进行排序,然后查看开始和结束以获得最小值和最大值。
使用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;
}
}
答案 0 :(得分:6)
排序最多为O(Nlog(N))。 您可以在O(n)中轻松地找到min和max,只是遍历数组。
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;
答案 1 :(得分:3)
排序成本O(NlogN),通过数组查找最小和最大成本O(N)。 不需要转换列表,只需对数组进行迭代。
答案 2 :(得分:0)
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)(请发布),它们在时间复杂度方面也是相同的。