Cover image for Interview Classic 150 Problem P162: Find Peak Element

Interview Classic 150 Problem P162: Find Peak Element


Timeline

Timeline

2025-12-03

init

Divide and Conquer

Problem:

  • If nums[mid] < nums[mid + 1], then the peak must be in the right half.
    Because it is increasing from left to right, and the rightmost is -∞, the right half must contain a peak (even if it is monotonically increasing, the last element is a peak).
  • If nums[mid] > nums[mid + 1], then the peak must be in the left half.
    Because it is increasing from right to left, and the leftmost is -∞, the left half must contain a peak.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
#include <vector>using std::vector;class Solution {    private:        bool isPeak(vector<int> &nums, int mid)        {                int n = nums.size();                if (mid != 0 && nums[mid] <= nums[mid - 1]) {                        return false;                }                if (mid != n - 1 && nums[mid] <= nums[mid + 1]) {                        return false;                }                return true;        }    public:        int findPeakElement(vector<int> &nums)        {                int n = nums.size();                int left = 0, right = n - 1, mid;                while (left <= right) {                        mid = left + (right - left) / 2;                        if (isPeak(nums, mid)) {                                return mid;                        }                        if (nums[mid] < nums[mid + 1]) {                                // If nums[mid] < nums[mid + 1], then the peak must be in the right half.                                // Because it is increasing from left to right, and the rightmost is -∞, the right half must contain a peak.                                left = mid + 1;                        } else {                                // If nums[mid] > nums[mid + 1], then the peak must be in the left half.                                // Because it is increasing from right to left, and the leftmost is -∞, the left half must contain a peak.                                right = mid - 1;                        }                }                return mid;        }};
Loading comments…