-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path153.寻找旋转排序数组中的最小值.py
68 lines (61 loc) · 1.43 KB
/
153.寻找旋转排序数组中的最小值.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#
# @lc app=leetcode.cn id=153 lang=python3
#
# [153] 寻找旋转排序数组中的最小值
#
# https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/description/
#
# algorithms
# Medium (50.01%)
# Likes: 116
# Dislikes: 0
# Total Accepted: 25.5K
# Total Submissions: 51K
# Testcase Example: '[3,4,5,1,2]'
#
# 假设按照升序排序的数组在预先未知的某个点上进行了旋转。
#
# ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
#
# 请找出其中最小的元素。
#
# 你可以假设数组中不存在重复元素。
#
# 示例 1:
#
# 输入: [3,4,5,1,2]
# 输出: 1
#
# 示例 2:
#
# 输入: [4,5,6,7,0,1,2]
# 输出: 0
#
#
from typing import List
# @lc code=start
class Solution:
def findMin(self, nums: List[int]) -> int:
"""
1. 遍历
"""
for i in range(len(nums) - 1):
if nums[i + 1] < nums[i]:
return nums[i + 1]
return nums[0]
def findMin_2(self, nums: List[int]) -> int:
"""
2. 二分查找
"""
if nums[-1] >= nums[0]:
return nums[0]
l, r = 0, len(nums) - 1
while l <= r:
mid = (l + r) // 2
if nums[mid] > nums[mid + 1]:
return nums[mid + 1]
elif nums[mid] < nums[0]: # 注意边界的等号情况
r = mid - 1
else:
l = mid + 1
# @lc code=end