Find Peak Element
Given an integer array nums where no two adjacent elements are equal, return the index of any peak element — an element strictly greater than both of its neighbors. Values just outside the array are treated as negative infinity. The algorithm must run in O(log n) time.
Open official problem prompt ↗Locate any local maximum in an array in logarithmic time without sorting or scanning it.
Hiking in fog: you cannot see the summit, but if the ground rises to your right you step right, and if it falls you step left. Following the uphill direction always brings you to a peak.
- Input
- nums = [1,2,3,1]
- Output
- 2
- Why
- nums[2] = 3 is greater than its neighbors 2 and 1, so index 2 is a valid peak.
1 <= nums.length <= 1000-2^31 <= nums[i] <= 2^31 - 1nums[i] != nums[i + 1] for all valid iImagined nums[-1] and nums[n] equal negative infinity