Example 1
- Input
- nums = [1,2,3,1]
- Output
- 2
Index 2 holds 3, strictly above its immediate neighbours 2 and 1. Return index 2 rather than value 3.
Given an array with no adjacent equals, return the index of any element strictly greater than its neighbours. Following the uphill slope always leads to a peak, which a binary search exploits in logarithmic time.
Given a 0-indexed integer array nums, find a peak element, and return its index. A peak element is an element that is strictly greater than its neighbors.
If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = nums[n] are , and you must write an algorithm that runs in time.
1 <= nums.length <= 1000-2^31 <= nums[i] <= 2^31 - 1nums[i] != nums[i + 1] for all valid i.Index 2 holds 3, strictly above its immediate neighbours 2 and 1. Return index 2 rather than value 3.
Indices 1 and 5 are both valid peaks: 2 exceeds its neighbours 1 and 1, while 6 exceeds 5 and 4. Either index is accepted; the illustrated output chooses 5.
The sole element is above both imaginary neighbours, even at the smallest allowed integer value. Return its index 0.
A peak is higher than both immediate neighbours; missing neighbours are considered lower than every input value. In [1, 2, 3, 1], index 2 holds 3, above 2 and 1. Following a rising step must eventually reach a fall or the right boundary, so some peak lies in that direction. We only need one peak, allowing binary search to retain a half with a guaranteed peak even if other peaks are discarded.
Reveal First Drop Scan: intuition, complexity, and code
[1, 3, 1, 3, 1] has peaks at indices 1 and 3; equal adjacent values are excluded.[-2147483648, 2147483647] returns 1 without arithmetic overflow.nums[mid + 1] with left <= right can go out of bounds. With left < right, the lower middle always has a right neighbour.right = mid - 1 can discard a peak at mid; setting left = mid can stall on a two-element rising interval.Binary search needs a halving decision, not a sorted array: a local slope that guarantees a peak in one half is enough.