Skip to content

Commit 990d17d

Browse files
Chris WuChris Wu
Chris Wu
authored and
Chris Wu
committed
search-in-rotated-sorted-array-ii.py
1 parent 7f9e795 commit 990d17d

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
We use binary search if the interval is sorted (`nums[l]<nums[r]`).
3+
If it is not sorted, we cut the array into half, to see
4+
* If the left half is sorted and the target is in the range. If so, look into the left part. (`r = p-1`)
5+
* If the right half is sorted and the target is in the range. If so, look into the right part. (`l = p+1`)
6+
* Else we can only move the `r` and `l` to the middle. (`r = r-1`, `l = l+1`). For example, `[1,1,1,1,1,1,1,3,1,1,1]`.
7+
The time complexity sits between, `O(LogN)` and `O(N)`.
8+
If there are a lots of the same value, we like `[1,1,1,1,1,1,1,3,1,1,1]` the time will closer to O(N). Vise versa.
9+
"""
10+
class Solution(object):
11+
def search(self, nums, t):
12+
if nums is None or len(nums)==0: return False
13+
l = 0
14+
r = len(nums)-1
15+
16+
while l<=r:
17+
p = (l+r)/2
18+
if nums[l]==t or nums[p]==t or nums[r]==t:
19+
return True
20+
21+
if nums[l]<nums[r]:
22+
#check if out of ragne
23+
if t<nums[l] or nums[r]<t: return False
24+
#binary search
25+
if t<nums[p]:
26+
r = p-1
27+
else:
28+
l = p+1
29+
else:
30+
if nums[l]<nums[p] and nums[l]<t and t<nums[p]:
31+
r = p-1
32+
elif nums[p]<nums[r] and nums[p]<t and t<nums[r]:
33+
l = p+1
34+
else:
35+
r = r-1
36+
l = l+1
37+
return False

problems/search-in-rotated-sorted-array.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,4 +131,3 @@ def search(self, nums, target):
131131

132132

133133

134-

0 commit comments

Comments
 (0)