2014-07-27 49 views
4

我試圖解決一個需要在數組中找到最大值的問題。該數組不能進行強力搜索,因爲它非常大(超過100,000,000個元素),所以我試圖創建二進制搜索的修改版本以查找最大值。從索引的任意一側查找數組中的最大值

數組的特定屬性是:

  • 陣列是圓形
  • 從最小值的陣列中的索引開始過去該索引的所有值將增加或保持不變,直到所述指數最大值。從這裏的值將保持不變或減少
  • 最小值的索引是最大值

某些陣列的實例是(所有等效陣列)的索引相對:

  • {1, 2, 3, 4, 5, 5, 4, 3, 2, 1}
  • {5, 4, 3, 2, 1, 1, 2, 3, 4, 5}
  • {3, 4, 5, 5, 4, 3, 2, 1, 1, 2}

有沒有人有任何想法來解決這個問題在大約O(logN)時間?

如何計算數組值:

unsigned long long calculateArrayValue(unsigned long long location, unsigned long long n, unsigned long long arrayLength, unsigned long long* arrayIndices, unsigned long long* locationMagnitude) { 
    unsigned long long value = 0; 
    unsigned long long halfArrayLength = arrayLength/ 2; 
    unsigned long long difference; 
    for (unsigned long long i = 0; i < n; i++) { 
     if (arrayIndices[i] > location) { 
      difference = arrayIndices[i] - location; 
     } else { 
      difference = location - houseLocations[i]; 
     } 
     if (difference > halfArrayLength) { 
      difference = arrayLength - difference; 
     } 
     value += difference * locationMagnitude[i]; 
    } 

    return value; 
} 
+0

你能否澄清「最小值的指數爲最大值的指數相反」。我沒有完全相反。 – Swapnil

+0

基本上說最小值的指數是6,最大值的指數是(6 + n/2)%n; – 1qaz0okm

回答

4

如果允許相同數量的N-1次和1次較大之一,例如列表

5 5 5 5 5 5 5 6 5,

然後我要求,你不能在一般情況下,解決問題在O(log n)的時間,因爲該問題是相當於搜索用於在1

所以你有效地尋找在未排序列表中的特定條目,該條目需要O(n)的時間。

當然,您可以加快特殊情況下的算法,例如,通過將線性搜索與二分搜索相結合,可以跳過嚴格減少列表的子序列。

以下解決方法是錯誤的,請參閱註釋。

僞代碼:

int next (int i) { 
    return i + 1 < length ? i + 1 : 0; 
} 

int prev (int i) { 
    return i - 1 < 0 ? length : i - 1; 
} 

int lower = 0; 
int upper = length - 1; 
int tmp; 

while (true) { 
    tmp = (upper + lower)/2; 
    if ((ary [prev(tmp)] <= ary [tmp]) && (ary [next(tmp)] <= ary [tmp])) break; 

    if (ary [prev(tmp)] <= ary [tmp]) { 
     lower = tmp; 
    } else if (ary [next(tmp)] <= ary [tmp]) { 
     upper = tmp; 
    } else { 
     /* we have found a minimum! */ 
     tmp = length - 1 - tmp; 
     break; 
    } 
} 

int maximum_index = tmp; 
+0

我有一些非常相似的東西,但它不適用於下面的示例(或任何數組,其中有3個同一數字在一行中): {5,5,5,5,5,6 ,5} – 1qaz0okm

+1

是的,你是對的。我的解決方案錯了。現在看來,你可以證明在O(log n)時間內解決問題是不可能的,因爲6可能在n個地方中的任何一個地方,並且一般來說,你不能確定它在哪裏通過查看(幾乎)所有的數組元素!?你基本上是在一個未排序的n-1個零和1個清單中尋找一個。 – JohnB

+0

因此,我花在嘗試尋找解決方案上的時間是徒勞的。有時候找到另一種方法來解決問題,然後:(。 – 1qaz0okm

相關問題