2013-02-11 131 views
-2

比方說,我有一個數組稱爲ArrL是由數字5,10,25,33,22,8和11。我的功能將需要數說21和找到的這個數字是「大於21,最接近21」,在這種情況下,這個數字是22.我該怎麼做?查找數組最大最接近給定數數

+3

嘗試去寫代碼,做這件事。 – BobTheBuilder 2013-02-11 08:40:46

+0

@PremGenError我想到的是試圖找到大於21的所有數字(在數組中)。然後將它們存儲在另一個數組中並查找最大數目的最小值。但其繁瑣,可能會導致大量的處理時間..但我想快速的方法.. :(..你能幫忙嗎? – 2013-02-11 09:41:46

+0

看起來像功課! – 2016-03-18 06:32:46

回答

0

迭代陣列,存儲最接近數字和位置。如果它更接近更新這些值。

1

因爲你的比較列表沒有排序,你必須檢查它的每一個元素。排序列表可以通過二進制搜索更高效地完成,但您的列表不是這種情況。

這個想法是在你瀏覽列表時記錄最接近但最大的數字,並在你找到一個更好的數字的地方更新它(比當前保存的更好但更接近),類似這樣的描述過程:

  1. 對於列表中的每個數字N,執行以下的步驟2至5以下。如果數字不足,請轉至步驟6.

  2. 如果N小於或等於您的目標號碼,請轉至第5步。這沒有意義。

  3. 如果R尚未設置(這N是你比你的目標發現更大的第一號),N保存爲返回值R,則轉到步驟5

  4. 如果N小於R,與N取代R,因爲它更接近。

  5. 返回步驟1查看下一個號碼。

  6. 如果你在上面的那些步驟設置R的東西,這就是你想要的值。否則,沒有高於您的目標數字的值。

下面的僞代碼是看它的另一種方式:

def greaterButClosest (list, find): 

    found = -1       # Initially none. 

    for idx = 0 to list.length:  # Check all indexes. 

    if list[idx] > find:    # Only consider those higher. 

     if found == -1:    # First one automatically closest. 
     found = idx 
     else: 
     if list[idx] < list[found]: # Otherwise, closer if less than current. 
      found = idx 

    if found == -1:     # Some sentinel if none found. 
    return -99999 

    return list[found]     # Otherwise return it. 

而且,作爲概念的證明,Python代碼:

def greaterButClosest (list, find): 
    found = -1 
    for idx in range (len(list)): 
     if list[idx] > find:     # < for opposite case. 
      if found == -1: 
       found = idx 
      else: 
       if list[idx] < list[found]: # > for opposite case. 
        found = idx 

    # <- Note indent level, this is OUTSIDE the for loop. 
    if found == -1: 
     return -99999 
    return list[found] 

for tst in [7, 8, 9, 10, 11, 99]: 
    print "%2d: %2d"%(tst, greaterButClosest ([5, 10, 25, 33, 22, 8, 11], tst)) 

其輸出:

7: 8 
8: 10 
9: 10 
10: 11 
11: 22 
99: -99999 
+0

哇..謝謝你@ paxdiablo.it工程.. :) – 2013-02-11 09:57:21

+0

@ paxdiablo..for找到小號數字是最接近21,我只需要改變>爲<? – 2013-02-11 10:36:04

+0

@凱文,在兩個地方顛倒了比較的意義,是的。首先要確保你只考慮數字_less_而不是目標'如果列表[idx] 列表[found]'下方靠近''。 – paxdiablo 2013-02-11 10:51:11

0

以下是您可能要遵循的幾個步驟: 1.按升序排列陣列 2.在陣列上執行線性搜索,以便顯示大於所選數字的第一個數字,並且它突破循環。 一個有序數組:

for(int i=0;i<ArrL.length;i++){ 
if(ArrL[i]>selected_no){ 
    System.out.println("The closest greater number is'+ArrL[i]); 
      break; 
    } 

}

+0

但是會有大量數字(在數組中)大於所選數字。 – 2013-02-11 09:39:18

+0

只要dis prog會發現第一個最大的數字就會跳出循環,因此停止搜索更多數字 – Sanghita 2013-02-12 06:55:39

1

你可以用這種方式

// To find Closest Number 
    NavigableSet<Integer> values = new TreeSet<Integer>(); 
    for (int x : listOfNum) { values.add(x); } 
    int lower = values.floor(number); 
    int higher = values.ceiling(number);