@@ -22,53 +22,113 @@ class Solution(object):
22
22
def search (self , nums , target ):
23
23
if not nums or len (nums )== 0 :
24
24
return - 1
25
-
25
+
26
26
l = 0
27
27
r = len (nums )- 1
28
28
while True :
29
29
m = (l + r )/ 2
30
-
30
+
31
31
left_num = nums [l ]
32
32
right_num = nums [r ]
33
33
mid_num = nums [m ]
34
-
34
+
35
35
if left_num == target :
36
36
return l
37
37
if right_num == target :
38
38
return r
39
39
if mid_num == target :
40
40
return m
41
-
41
+
42
42
#break the array into two part
43
43
#l~m and m~r
44
-
44
+
45
45
if left_num < target and target < mid_num :
46
46
#l~m is sorted and target is inside
47
47
#do the same calculation to this part
48
48
r = m - 1
49
49
continue
50
-
50
+
51
51
if mid_num < target and target < right_num :
52
52
#m~r is sorted and target is inside
53
53
#do the same calculation to this part
54
54
l = m + 1
55
55
continue
56
-
56
+
57
57
#if the code goes here
58
58
#the target doesn't exist or
59
59
#one of two part is not sorted
60
60
#the target is in the not sorted part
61
-
61
+
62
62
if mid_num > right_num :
63
63
#m~r is not sorted
64
64
#check m+1~r
65
65
l = m + 1
66
66
continue
67
-
67
+
68
68
if mid_num < left_num :
69
69
#l~m is not sorted
70
70
#check l~m-1
71
71
r = m - 1
72
72
continue
73
73
74
74
return - 1
75
+
76
+
77
+ """
78
+ If we slice (anywhere) in the rotated-sorted-array, there must be one part already sorted, another part still rotated.
79
+ If the right most elemant in the array is greater than the left most (`nums[l]<nums[r]`), then it is **sorted**.
80
+ If the array is sorted, we can apply binary search in it.
81
+
82
+ So for every part of the array, we first determine if it is sorted.
83
+ If it is sorted apply binary search.
84
+ If it is not sorted, check if the target in the sorted part. If not, search the other part.
85
+ """
86
+ class Solution (object ):
87
+ def search (self , nums , target ):
88
+ if nums is None or len (nums )== 0 : return - 1
89
+
90
+ l = 0
91
+ r = len (nums )- 1
92
+
93
+ while l <= r :
94
+ p = (l + r )/ 2
95
+
96
+ if nums [l ]== target : return l
97
+ if nums [p ]== target : return p
98
+ if nums [r ]== target : return r
99
+
100
+ #array sorted
101
+ if nums [l ]< nums [r ]:
102
+ #binary search
103
+
104
+ #check target is in range
105
+ if target < nums [l ] or nums [r ]< target :
106
+ return - 1
107
+
108
+ if target < nums [p ]:
109
+ r = p - 1
110
+ else :
111
+ l = p + 1
112
+
113
+ #array not sorted
114
+ else :
115
+ #the left half is sorted
116
+ if nums [l ]< nums [p ]:
117
+ #the left half is sorted and target in it, search left.
118
+ if nums [l ]< target and target < nums [p ]:
119
+ r = p - 1
120
+ else :
121
+ l = p + 1
122
+
123
+ #the right half is sorted
124
+ else :
125
+ #the right half is sorted and target in it, search right.
126
+ if nums [p ]< target and target < nums [r ]:
127
+ l = p + 1
128
+ else :
129
+ r = p - 1
130
+ return - 1
131
+
132
+
133
+
134
+
0 commit comments