LintCode Q62 Search in Rotated Sorted Array in Python

  • Jinhai ZHOU
  • 7 Minutes
  • 2016年12月25日
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
class Solution:
"""
@param A : a list of integers
@param target : an integer to be searched
@return : an integer
"""
def search(self, A, target):
# write your code here
# no duplicates
# 1st step: find break point
if len(A) == 0:
return -1
lo, hi = 0, len(A) - 1
if A[lo] < A[hi]:
return self.binarySearch(A, target, lo, hi)
[left, right] = [-1, -1]
while lo <= hi:
mid = lo + (hi - lo)/2
if mid < len(A) - 1 and A[mid] > A[mid + 1]:
[left, right] = [mid, mid + 1]
break
elif mid > 0 and A[mid - 1] > A[mid]:
[left, right] = [mid - 1, mid]
break
elif A[mid] < A[len(A)-1]:
hi = mid - 1
elif A[mid] > A[0]:
lo = mid + 1
else: # when len(A) == 1
if A[mid] == target:
return mid
else:
return -1
if left == -1:
return -1
lo, hi = 0, len(A) - 1
left = self.binarySearch(A, target, lo, left)
right = self.binarySearch(A, target, right, hi)
if left == -1:
return right
else:
return left
# 2nd step: perform 2 binary search
def binarySearch(self, A, target, lo, hi):
while lo <= hi:
mid = lo + (hi - lo)/2
if A[mid] < target:
lo = mid + 1
elif A[mid] > target:
hi = mid - 1
else:
return mid
return -1
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。