-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearch_in_Rotated_Sorted_Array 2.py
More file actions
59 lines (42 loc) · 1.07 KB
/
Copy pathSearch_in_Rotated_Sorted_Array 2.py
File metadata and controls
59 lines (42 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
"""
class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return an integer
def search(self, A, target):
if A == None:
return False
start = 0
end = len(A) - 1
while (start <= end):
mid = (start + end) / 2
# found
if A[mid] == target: return True
# left half is sorted
if A[mid] > A[start]:
# target in left half
if A[start] <= target < A[mid]:
end = mid - 1
# target in right half
else:
start = mid + 1
# right half is sorted
elif A[mid] < A[start]:
# target in right half
if A[mid] < target <= A[end]:
start = mid + 1
# target in left half
else:
end = mid - 1
# duplication occured move one step
else:
start += 1
# not found
return False
s = Solution()
print s.search([1,1,1,3], 1)