# A concise standard binary search solution

• int findPeakElement(const vector<int> &num) {
if (num.size() <= 1) return 0;
int mid = 0, l = 0, h = num.size() - 1;

while (l < h) {
mid = (l + h) / 2;
if (num[mid] > num[mid + 1])
h = mid;
else if (num[mid] < num[mid + 1])
l = mid + 1;
}

return l;
}

• This is a very concise and a very smart solution, but the function does not follow a standard binary search format. I prefer to use the a bit more complicated but standard binary search function. It is much easier to write a bug free code.

• if num[mid] > num[mid+1] , then we found our peak elem , right?

• how about this test case: [7, 6, 5, 3, 2, 5, 4]? I got 0 in this case. Please help..

• @homerhickam , if num[mid]>num[mid+1], then we can know the peak is in the [l, m] span

• @cjhuo, i think index 0 is also a peak , according to " num[-1] = num[n] = -∞ "

• Im wondering what if the input happened to be [1,1,1,2]... it seems that you will be in the loop forever...

• yes, but the input condition is: "Given an input array where num[i] ≠ num[i+1]"

• The first line if (num.size() <= 1) return 0; can be removed. If the size is less than 2, while loop will be skipped and 0 will be returned.

• @forytest , you are right!

• why do you think this is not standard ?

• I still do not understand why the final peak element will locate at l. Why not r? Could you explain to me?

• I agree with you.

• test case [0,3,2,1,4] num[mid] > num[mid+1] then peak is in the [low, mid], but 4 is still a peak.

• @dianren ,Given num[-1] = num[n] = -∞, if num[mid] > num[mid+1], there is at least one peak in [low, mid], and there may be one peak in [mid+1, high].

• This post is deleted!

• I guess return either h or l is both correct, in the end, l=h.

• I have a pretty general question regarding binary search: sometimes the termination condition is left < right, other times it's left <= right. Anyone knows when to use which? Thanks!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.