簡體   English   中英

查找數組中大於設定限制的最小元素:java

[英]finding the smallest element in an array that is greater than a set limit: java

我正在嘗試編寫一個函數,該函數循環遍歷列表一次並打印出大於設定限制的最小元素的索引。

非正式地使用 == 這是預期的輸出:

0 == posOfSmallestElementGtOeT(3, new double[] { 7 })

3 == posOfSmallestElementGtOeT(3, new double[] { 11, -4, -7, 4, 8, 1 })

-1 == posOfSmallestElementGtOeT(17, new double[] { 1, -4, -5, 7, 8, 11 })

到目前為止我有這個。 我可以找到大於設置限制的元素,但無法弄清楚如何正確比較它們。

public static int posOfSmallestElementGtOeT( double limit, double[] list) {
    double greater = 0;
    int pos = 0;
    for(int i=0; i < list.length; i++) {
        if(list[i] >= limit) {
            System.out.println(list[i]);
            //for testing
        }
    }
    return pos;
}

目前我的函數返回大於設置限制的最后一個值。 有人可以指導我如何找到這些 vals 中最小的一個。

這將解決您的問題。

public static int posOfSmallestElementGtOeT( double limit, double[] list) {
    double greater = 0;
    int pos = -1;
    for(int i=0; i < list.length; i++) {
        if(list[i] >= limit) {
            if(pos == -1) // check whether its the first value above the limit in the list
                pos = i;
            else if(list[pos] > list[i]) //compare the current value with the previous smallest value
                pos = i;
        }
    }
    return pos;
}

對於大於閾值的第一個元素,您直接保存它的位置。 對於下一個,您將當前最佳候選 ( list[pos] ) 與當前元素 ( list[i] ) 進行比較:如果第一個大於第二個,則有比前者更好的候選,因此位置將被返回的方法將被更新。

示例: threshold :1.5
myArray : 2, 1.6, 1.4, -5.2

  1. 第一個元素大於閾值,所以設置變量pos = 0
  2. 第二個元素大於閾值,但 pos != -1,因此您評估第二個條件: list[0] > list[1] ,或 2 > 1.6。
  3. 條件為真,所以你更新pos = 1 的值

通過這種方式,您只需循環一次即可找到預期結果,成本為 O(N),其中 N 是數組的項目數(線性成本)。


請注意,大於或等於閾值的最小元素應該不存在,如下例所示:

threshold :1.5
myArray : 0.3, 0.6, 1.4, -5.2

在這種情況下,該方法將返回 -1 並且調用應正確管理該結果,例如:

if(posOfSmallestElementGtOeT( threshold, myArray) == -1) {
    System.out.println("No element greater or equal to the threshold");
}

在網頁上我如何提出一個好問題? ,據說好問題的標准之一是研究。 你的問題給我的印象是你沒有。 在互聯網上搜索條款最小的數組元素大於最小打開了一個實現Python中,如下所示:

min_val = 10000000
for i in test_list : 
    if min_val > i and i > k : 
        min_val = i

我毫不費力地將該代碼翻譯成 Java——即使我根本不懂 Python。 不同之處在於您請求了元素的位置,而上面的代碼返回了實際的元素值。 同樣,修改上面的代碼(將其轉換為 java 之后)似乎並不太難,以便它返回元素索引而不是元素值。

public static int posOfSmallestElementGtOeT(double limit, double[] list) {
    double min = Double.MAX_VALUE;
    int ndx = -1;
    for (int i = 0; i < list.length; i++) { 
        if (min >= list[i] && list[i] >= limit) { 
            min = list[i];
            ndx = i;
        }
    }
    return ndx;
}

請注意,上面的代碼也適用於空數組。
(但空數組會拋出NullPointerException :-)

假設list至少包含一個元素:

public static int posOfSmallestElementGtOeT(double limit, double[] list) {
    double greater = list[0];

    int pos = greater >= limit ? 0 : -1;

    for(int i = 1; i < list.length; i++) {
        if(list[i] >= limit && list[i] < greater) {
            pos = i;
            greater = list[i];
        }
    }
    return pos;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM