[英]How would I find the index of the smallest value in an int array?
我對java還是很陌生,所以我想保持簡單,我想我必須采用數組的第一個值,然后將其與每個后續值進行比較,如果該值大於第一個值,則替換價值,但我不知道如何從中獲取索引。
對於一個非結構化,未排序的數組,假設僅要查找一次最小值,那么您可以做的最好的事情是對所有元素進行一次簡單的迭代( O(n)復雜度),如下所示:
public int findMinIdx(int[] numbers) {
if (numbers == null || numbers.length == 0) return -1; // Saves time for empty array
// As pointed out by ZouZou, you can save an iteration by assuming the first index is the smallest
int minVal = numbers[0] // Keeps a running count of the smallest value so far
int minIdx = 0; // Will store the index of minVal
for(int idx=1; idx<numbers.length; idx++) {
if(numbers[idx] < minVal) {
minVal = numbers[idx];
minIdx = idx;
}
}
return minIdx;
}
同樣,如果為最小值,則此方法將返回找到的該值的第一種情況的索引。 如果希望它是最后一種情況,只需將numbers[idx] < minVal
為numbers[idx] <= minVal
。
這是Java 8
public static int findMinIdx(int[] numbers) {
OptionalInt minimun = IntStream.of(numbers).min();
return IntStream.of(numbers).boxed().collect(toList()).indexOf(minimun.getAsInt());
}
從不關心運行時優化,只是在尋找解決方案!,它奏效了,這對您也有幫助,可以找到數組中最低值的索引。
// array[] -> Received the array in question as an parameter
// index -> stores the index of the lowest value
// in for loop, i is important to complete all the comparison in the function
// When it finds a lower value between the two, it does not change the index
// When it finds a lower value it changes it's index to that index
// If array has same value more than once, it will provide index to that values last occurrence
// Correct me if you find anything not working in this example...
//...
private static int index_of_minimum_value(int[] array) {
int index = 0;
for (int i = 1; i < array.length; i++) {
if ((array[i - 1] < array[i]) && ([index] > array[i - 1])) index = i - 1;
else if (array[index] > array[i]) index = i;
}
return index;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.