Skip to content

Commit 704af3f

Browse files
Search in Rotated Sorted Array
Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Example Example 1: Input: [4, 5, 1, 2, 3] and target=1, Output: 2. Example 2: Input: [4, 5, 1, 2, 3] and target=0, Output: -1.
1 parent ece667b commit 704af3f

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Search in Rotated Sorted Array

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution:
2+
"""
3+
@param A: an integer rotated sorted array
4+
@param target: an integer to be searched
5+
@return: an integer
6+
"""
7+
def search(self, A, target):
8+
# write your code here
9+
if not A:
10+
return -1
11+
12+
start, end = 0, len(A) - 1
13+
while start+1 < end:
14+
mid = (start + end) // 2
15+
if A[mid] > A[start]:
16+
if A[start] <= target <= A[mid]:
17+
end = mid
18+
else:
19+
start = mid
20+
else:
21+
if A[mid] <= target <= A[end]:
22+
start = mid
23+
else:
24+
end = mid
25+
26+
if A[start] == target:
27+
return start
28+
elif A[end] == target:
29+
return end
30+
else:
31+
return -1

0 commit comments

Comments
 (0)