-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path162.py
48 lines (35 loc) · 1.42 KB
/
162.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
峰值元素是指其值大于左右相邻值的元素。
给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。
数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。
你可以假设 nums[-1] = nums[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。
说明:
你的解法应该是 O(logN) 时间复杂度的。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-peak-element
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from typing import List
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
def helper(left_idx, right_idx):
if left_idx == right_idx:
return left_idx
mid_idx = (left_idx + right_idx) // 2
if nums[mid_idx] < nums[mid_idx+1]:
return helper(mid_idx + 1, right_idx)
else:
return helper(left_idx, mid_idx)
return helper(0, len(nums)-1)
nums = [1, 2, 1, 3, 5, 6, 4]
nums = [1, 2, 3, 1]
print(Solution().findPeakElement(nums))