Skip to content

Commit bef959b

Browse files
committed
数组局部峰值(二分搜索, 注意边界确定)
1 parent 99e158b commit bef959b

File tree

2 files changed

+47
-2
lines changed

2 files changed

+47
-2
lines changed

BinarySearch/162_FindPeakElement.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# coding: utf8
2+
3+
4+
"""
5+
题目链接: https://leetcode.com/problems/find-peak-element/description.
6+
题目描述:
7+
8+
A peak element is an element that is greater than its neighbors.
9+
10+
Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
11+
12+
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
13+
14+
You may imagine that num[-1] = num[n] = -∞.
15+
16+
For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
17+
18+
click to show spoilers.
19+
20+
Note:
21+
Your solution should be in logarithmic complexity.
22+
23+
Credits:
24+
Special thanks to @ts for adding this problem and creating all test cases.
25+
26+
"""
27+
28+
29+
class Solution(object):
30+
def findPeakElement(self, nums):
31+
"""
32+
:type nums: List[int]
33+
:rtype: int
34+
"""
35+
left, right = 0, len(nums) - 1
36+
# 局部峰值落在哪个半区
37+
while left < right:
38+
mid = left + (right - left) // 2
39+
if nums[mid] < nums[mid + 1]:
40+
left = mid + 1
41+
else:
42+
right = mid
43+
44+
return right

README.md

+3-2
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,14 @@ leetcode刷题, 直接用leetcode的分类方式.
33

44
- [x] 数组 (完成时间: 2018-01-23)
55
- 字符串
6-
- 链表
6+
- [x] 链表 (完成时间: 2018-01-28)
77
- 哈希表
88
- 堆栈
99
- 双指针
10-
-
10+
- [x] 树 (完成时间: 2018-02-04)
1111
-
1212
- 深搜/广搜
13+
- [x] 二分搜索 (完成时间: 2018-02-06)
1314
- 动规
1415
- 其他: 数学, 位操作, 设计题等
1516

0 commit comments

Comments
 (0)