[英]Finding max value in array with increasing values from either side of an index
我試圖解決一個需要在數組中找到最大值的問題。 數組不能被強力搜索,因為它非常大(超過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;
}
如果您允許n-1次相同的數字列表和1次更大的列表,例如
5 5 5 5 5 5 5 6 5,
然后我聲稱你通常不能在O(log n)時間內解決問題,因為問題相當於搜索1 in
0 0 0 0 0 0 0 1 0
因此,您有效地在未排序列表中搜索特定條目,這需要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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.