-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathleetcode_033.py
More file actions
41 lines (39 loc) · 1.07 KB
/
leetcode_033.py
File metadata and controls
41 lines (39 loc) · 1.07 KB
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
# leetcode 33. 搜索旋转排序数组
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
#先找到两个第二个升序数组的第一项的
l = 0
r = len(nums) -1
while l < r:
mid = (l + r)//2
if nums[mid] > nums[r]:
l = mid + 1
else:
r = mid
pol = l
ans = self.binary_search(target, nums[:pol])
if ans == -1:
ans = self.binary_search(target, nums[pol:])
if ans != -1:
ans += len(nums[:pol])
return ans
# 二分查找index值函数
def binary_search(self, target, nums):
index = -1
l = 0
r = len(nums) - 1
while l <= r:
mid = (l+r)//2
if nums[mid] < target:
l = mid + 1
elif nums[mid] > target:
r = mid - 1
else:
index = mid
break
return index