[英]Efficient way for finding the min and max value in an array
我想找出整数数组中的最小值和最大值。
以下哪种方式效率更高?
对数组进行排序,然后查看开始和结束以获得最小值和最大值。
使用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;
}
}
排序最多为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]
}
编辑:
我注意到你粘贴了一些额外的代码,并且你实际上想要在一个连续数字的数组中找到一个缺失的数字。 而不是迭代那么多,有数学总结可以帮助你在这里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;
分类成本O(NlogN),通过一个数组来查找最小和最大成本O(N)。 无需转换列表,只需对数组进行处理即可。
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)(请发布),它们在时间复杂度方面也是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.