# Sharing a more standard Binary Search C++ Solution

• ``````class Solution {
public:
int findPeakElement(const vector<int> &num) {
int low = 0, high = num.size() - 1;
while (low < high - 1) {
int mid = (low + high) / 2;
if (num[mid] > num[mid - 1] && num[mid] > num[mid + 1])
return mid;
else if (num[mid] > num[mid + 1])
high = mid - 1;
else
low = mid + 1;
}
return num[low] > num[high] ? low : high;
}
};``````

• I don't understand why your solution is correct (although it is accepted by the oj system). Try this test case:
num = {1, 2, 1, 1, 1, 1};

• First, this case {1, 2, 1, 1, 1, 1} is not RIGHT. It does NOT satisfy "Given an input array where num[i] ≠ num[i+1]" , and with that requirement together with this "num[n] & num[-1] = -∞", they're very important. They guarantee that the peak could always exist and then guarantee the correctness of binary search for this problem.

• Sorry, you are right. And your solution is excellent. I forget the condition that "num[i] ≠ num[i+1]".

• Thank you :)

• i think this is wrong answer.
for example:
[1,9,2,3,4,5,6,7]
but the right answer is 9.

• actually 7 is also a right answer:) you can read the question again~

• oh,you are right. (^__^)

• This post is deleted!

• a more concise solution:

``````int findPeakElement(vector<int>& nums) {
int l = 0, r(nums.size());
while(l < r){
int mid = l + (r-l) / 2;
if(mid == l) break;
if(nums[mid] > nums[mid-1]) l = mid;
else r = mid;
}
return l;
}``````

• This post is deleted!

• ``````    while (low < high - 1) {
``````

Why `while (low < high - 1) {` not `while (low < high)` ? Isn't the latter more standard for binary search problems?

• Awesome solution.

Same Solution with recursive approach:

``````int helper(vector<int> &nums,int left,int right){
if(left == right){
return right;
}
int mid = (left+right)/2;
if(nums[mid]>nums[mid+1] && nums[mid]>nums[mid-1]){
return mid;
}else if(nums[mid] > nums[mid+1]){
return helper(nums,left,mid);
}else{
return helper(nums,mid+1,right);
}
}
``````

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