[英]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.