简体   繁体   中英

is the asymptotic time complexity of this algorithm O(log n)?

The psuedocode algorithm to find p is:

peakreturn(H)
for p=1 to m //m is the length of H
    if H[p-1] ≤ H[p] and H[p] ≥ H[p+1] then return p
return nil // only returns this if there is no peak

Let's say I have an array H[1 through m] of int values where "p" is the peak element if:

H[p] ≥ H[p+1] if p = 1,
H[p-1] ≤ A[p] ≥ H[p+1] if 1 < p < m,
H[p] ≥ H[p-1] if p = m.

Basically, H[p] is the peak if it is greater than or equal to its neighbor elements.

It's assumed that the array H is larger by 1 element at the beginning and the end, the array is H[0 to m+1], where H[0] = H[m+1] = -infinity. Therefore, H[0] and H[m+1] are sentinels. Then an element p, where 1 ≤ p ≤ n, is a peak if H[p-1] ≤ H[p] ≥ H[p+1].

I think the asymptotic time complexity is O(log n) but I'm not sure. Please help if you can, thanks so much.

No, it's not O(log m). For example, if H is increasing then the loop executes m times since the only peak is the last element. So the worst case is O(m).

An O(log m) solution looks like this: to find a peak in an array where the end elements are smaller than their neighbours, consider the middle element of the array. If it is a peak, then stop. Otherwise, if it's smaller than the element on its left, find a peak in the left half of the array. If it's smaller than the element on its right, find a peak in the right half of the array. It must be smaller than one or the other, since it's not a peak. This approximately halves the size of the array each time, and it's guaranteed to terminate since as soon as the array gets to size 3, the middle element is guaranteed to be a peak, since the end elements are (by construction) smaller than their neighbour -- the middle element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM