Find an Array's Local Peak
In various data analysis and optimization scenarios, identifying "peaks" or local maxima within a dataset is a common task. A peak element represents a point that is greater than its immediate neighbors, signifying a local high point or an inflection point in a sequence. This challenge asks you to efficiently locate one such peak within a given array.
Problem Description
You are given an integer array nums, where nums[i] != nums[i+1] for all valid i. Your task is to find a peak element and return its index.
A peak element is an element that is strictly greater than its neighbors. For elements at the boundaries:
- For the first element
nums[0], its only neighbor to consider isnums[1]. We can imaginenums[-1] = -∞. - For the last element
nums[n-1], its only neighbor to consider isnums[n-2]. We can imaginenums[n] = -∞.
This means an element nums[i] is a peak if:
nums[i] > nums[i-1](ifi > 0) ANDnums[i] > nums[i+1](ifi < n-1).- If
i = 0,nums[0] > nums[1]. - If
i = n-1,nums[n-1] > nums[n-2].
It is guaranteed that there will always be at least one peak element in the array. If there are multiple peaks, returning the index to any one of them is acceptable.
Examples
Example 1:
Input: nums = [1, 2, 3, 1]
Output: 2
Explanation: 3 is a peak element, and its index is 2. (nums[2] > nums[1] and nums[2] > nums[3])
Example 2:
Input: nums = [1, 2, 1, 3, 5, 6, 4]
Output: 5
Explanation: 6 is a peak element, and its index is 5. (nums[5] > nums[4] and nums[5] > nums[6])
Note that 2 is also a peak element at index 1. Returning either 1 or 5 would be correct.
Example 3:
Input: nums = [7, 6, 5, 4, 3, 2, 1]
Output: 0
Explanation: The first element 7 is a peak because we can imagine nums[-1] = -∞, and 7 > -∞ and 7 > 6.
Constraints
1 <= nums.length <= 1000-2^31 <= nums[i] <= 2^31 - 1nums[i] != nums[i+1]for all validi.- You must write an algorithm that runs in
O(log N)time.
Notes
- Remember the implicit condition
nums[-1] = nums[n] = -∞when considering the boundary elements. This simplification guarantees that a peak will always exist. - The
O(log N)time complexity constraint strongly suggests an approach similar to binary search. Think about how you can eliminate half of the search space in each step based on the relationship betweennums[mid]and its neighbors.