LeetCode 题解工作台
寻找峰值
峰值元素是指其值严格大于左右相邻值的元素。 给你一个整数数组 nums ,找到峰值元素并返回其索引。数组可能包含多个峰值,在这种情况下,返回 任何一个峰值 所在位置即可。 你可以假设 nums[-1] = nums[n] = -∞ 。 你必须实现时间复杂度为 O(log n) 的算法来解决此问题。 …
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
我们定义二分查找的左边界 ,右边界 ,其中 是数组的长度。在每一步二分查找中,我们找到当前区间的中间元素 ,然后比较 与其右边元素 的值: - 如果 的值大于 的值,则左侧存在峰值元素,我们将右边界 更新为 ;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
峰值元素是指其值严格大于左右相邻值的元素。
给你一个整数数组 nums,找到峰值元素并返回其索引。数组可能包含多个峰值,在这种情况下,返回 任何一个峰值 所在位置即可。
你可以假设 nums[-1] = nums[n] = -∞ 。
你必须实现时间复杂度为 O(log n) 的算法来解决此问题。
示例 1:
输入:nums = [1,2,3,1]
输出:2
解释:3 是峰值元素,你的函数应该返回其索引 2。
示例 2:
输入:nums = [1,2,1,3,5,6,4]
输出:1 或 5
解释:你的函数可以返回索引 1,其峰值元素为 2;
或者返回索引 5, 其峰值元素为 6。
提示:
1 <= nums.length <= 1000-231 <= nums[i] <= 231 - 1- 对于所有有效的
i都有nums[i] != nums[i + 1]
解题思路
方法一:二分查找
我们定义二分查找的左边界 ,右边界 ,其中 是数组的长度。在每一步二分查找中,我们找到当前区间的中间元素 ,然后比较 与其右边元素 的值:
- 如果 的值大于 的值,则左侧存在峰值元素,我们将右边界 更新为 ;
- 否则,右侧存在峰值元素,我们将左边界 更新为 。
- 最后,当左边界 与右边界 相等时,我们就找到了数组的峰值元素。
时间复杂度 ,其中 是数组 的长度。每一步二分查找可以将搜索区间减少一半,因此时间复杂度为 。空间复杂度 。
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) >> 1
if nums[mid] > nums[mid + 1]:
right = mid
else:
left = mid + 1
return left
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Assessing the candidate's understanding of binary search and its application to specific problems.
- question_mark
Looking for clarity in explaining why binary search works for this problem, especially with edge cases.
- question_mark
Evaluating the candidate's ability to write efficient, optimal code without unnecessary operations.
常见陷阱
外企场景- error
Misunderstanding the concept of a peak at the edges of the array, especially when dealing with virtual boundaries (-∞).
- error
Forgetting to check both neighbors during the binary search, potentially missing the peak element.
- error
Using a brute-force approach that results in higher time complexity instead of utilizing binary search.
进阶变体
外企场景- arrow_right_alt
Modify the problem to return all peak elements instead of just one.
- arrow_right_alt
Extend the problem to find the global peak that is strictly larger than all elements in the array.
- arrow_right_alt
Test variations on arrays with repeated elements and adapt the peak definition accordingly.