-
Notifications
You must be signed in to change notification settings - Fork 1
/
080 Search in Rotated Sorted Array II.py
112 lines (100 loc) · 3.1 KB
/
080 Search in Rotated Sorted Array II.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
"""
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.
Author: Rajeev Ranjan
"""
class Solution:
def search_set(self, A, target):
"""
Follow up 033 Search in Rotated Sorted Array
Duplicate allowed
rotated cases:
target is 3
start mid end
case 1:
1, 1, 1, 1, 1, 3, 1
case 2:
1, 3, 1, 1, 1, 1, 1
Algorithm: eliminate duplicates
:param A: a list of integers
:param target: an integer
:return: a boolean
"""
A = list(set(A)) # short-cut eliminate duplicates # but O(n)
length = len(A)
start = 0
end = length-1
while start<=end:
mid = (start+end)/2
# found
if A[mid]==target:
return True
# case 1
if A[start]<A[mid]<A[end]:
if target>A[mid]:
start = mid+1
else:
end = mid-1
# case 2
elif A[start]>A[mid] and A[mid]<A[end]:
if target>A[mid] and target<=A[end]:
start = mid+1
else:
end = mid-1
# case 3
else:
if target<A[mid] and target>=A[start]:
end = mid-1
else:
start = mid+1
return False
def search(self, A, target):
"""
Follow up 033 Search in Rotated Sorted Array
Duplicate allowed
rotated cases:
target is 3
start mid end
case 1:
1, 1, 1, 1, 1, 3, 1
case 2:
1, 3, 1, 1, 1, 1, 1
Algorithm: advance pointer if undetermined
:param A: a list of integers
:param target: an integer
:return: a boolean
"""
length = len(A)
start = 0
end = length-1
while start<=end:
mid = (start+end)/2
# found
if A[mid]==target:
return True
# undetermined # the only significant difference.
if A[start]==A[mid]:
start += 1
# case 1
elif A[start]<A[mid]<=A[end]:
if target>A[mid]:
start = mid+1
else:
end = mid-1
# case 2
elif A[start]>A[mid] and A[mid]<=A[end]: # slight difference compared to A[mid]<A[end]
if target>A[mid] and target<=A[end]:
start = mid+1
else:
end = mid-1
# case 3
else:
if target<A[mid] and target>=A[start]:
end = mid-1
else:
start = mid+1
return False
if __name__=="__main__":
assert Solution().search([1,1,3,1], 3)==True