Problem · Array
Find a Deterministic Local Minimum
Learn this problemProblem statement
You are given a non-empty integer array nums. An index i is a local minimum when its value is no greater than each existing neighbor. Treat a missing neighbor outside the array as positive infinity.
Return the index selected by this deterministic binary-search rule:
- Search the inclusive range
[left,right]and usefloor((left+right)/2)asmid. - If
nums[mid]is a local minimum, returnmid. - Otherwise, if the left neighbor is strictly smaller than
nums[mid], continue in the left half. - Otherwise continue in the right half.
This rule handles equal neighbors without requiring a strict local minimum.
Function
findLocalMinimum(nums: int[]) → intExamples
Example 1
nums = [9,7,3,5,8]return = 2The first midpoint is index 2, and 3 is no greater than either neighbor.
Example 2
nums = [4]return = 0The only element has no existing neighbor and is therefore a local minimum.
Example 3
nums = [3,2,2,4]return = 1Index 1 is the first midpoint and its value is no greater than either neighbor, including the equal value on its right.
Constraints
numsis non-empty.- Every value fits in a signed
32-bit integer. - Equal adjacent values are allowed.