Jack Li's Blog

0852. Peak Index in a Mountatin Array

class Solution {
public:
    int peakIndexInMountainArray(vector<int>& arr) {
        int l = 0;
        int r = arr.size() - 1;
        int mid;
        // Use l < r rather than l <= r because I want to stop at l == r
        // Seems like no effect in this question
        while(l < r){
            mid = l + (r - l) / 2;
            // Current is peak if left and right are smaller than mid
            if(arr[mid-1] < arr[mid] && arr[mid] > arr[mid+1]){
                return mid;
            }
            // Only move to mid to avoid illegal condition
            if(arr[mid-1] < arr[mid]){
                l = mid;
            } else {
                r = mid;
            }
        }

        return l;
    }
};