-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path33.搜索旋转排序数组.py
More file actions
61 lines (61 loc) · 1.5 KB
/
33.搜索旋转排序数组.py
File metadata and controls
61 lines (61 loc) · 1.5 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#
# @lc app=leetcode.cn id=33 lang=python
#
# [33] 搜索旋转排序数组
#
# https://leetcode-cn.com/problems/search-in-rotated-sorted-array/description/
#
# algorithms
# Medium (36.14%)
# Likes: 355
# Dislikes: 0
# Total Accepted: 43K
# Total Submissions: 119K
# Testcase Example: '[4,5,6,7,0,1,2]\n0'
#
# 假设按照升序排序的数组在预先未知的某个点上进行了旋转。
#
# ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
#
# 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
#
# 你可以假设数组中不存在重复的元素。
#
# 你的算法时间复杂度必须是 O(log n) 级别。
#
# 示例 1:
#
# 输入: nums = [4,5,6,7,0,1,2], target = 0
# 输出: 4
#
#
# 示例 2:
#
# 输入: nums = [4,5,6,7,0,1,2], target = 3
# 输出: -1
#
#
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low=0
high=len(nums)-1
while low<=high:
mid=low+(high-low)/2
if nums[mid]==target:
return mid
if nums[mid]>=nums[low]:
if nums[low]<=target<=nums[mid]:
high=mid-1
else:
low=mid+1
else:
if nums[mid]<=target<=nums[high]:
low=mid+1
else:
high=mid-1
return -1