问题描述
A peak element is an element that is greater than its neighbors.
Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that nums[-1] = nums[n] = -∞.
Example 1:
1 | Input: nums = [1,2,3,1] |
Example 2:
1 | Input: nums = [1,2,1,3,5,6,4] |
Follow up: Your solution should be in logarithmic complexity.
解题思路
二分查找
思路是用二分法,因为题目要求时间复杂度是
log
级别。根据左右指针计算中间位置m,并比较m
与m+1
的值,如果m
较大,则左侧存在峰值,r = m
,如果m + 1
较大,则右侧存在峰值,l = m + 1
代码如下:
JavaScript
1 | /** |
- 时间复杂度:O(logn)
- 空间复杂度:O(1)