Skip to content

Commit ab7b041

Browse files
committed
Search in Rotated Sorted Array
1 parent 2cada58 commit ab7b041

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

033-search-in-rotated-sorted-array.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/search-in-rotated-sorted-array/
3+
4+
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
5+
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
6+
You are given a target value to search. If found in the array return its index, otherwise return -1.
7+
You may assume no duplicate exists in the array.
8+
Your algorithm's runtime complexity must be in the order of O(log n).
9+
10+
Example 1:
11+
Input: nums = [4,5,6,7,0,1,2], target = 0
12+
Output: 4
13+
14+
Example 2:
15+
Input: nums = [4,5,6,7,0,1,2], target = 3
16+
Output: -1
17+
"""
18+
class Solution(object):
19+
def search(self, nums, target):
20+
"""
21+
:type nums: List[int]
22+
:type target: int
23+
:rtype: int
24+
"""
25+
start = 0
26+
end = len(nums) - 1
27+
while start <= end:
28+
mid = (start + end)//2
29+
if nums[mid] == target:
30+
return mid
31+
elif nums[start] <= nums[mid]:
32+
if target >= nums[start] and target < nums[mid]:
33+
end = mid -1
34+
else:
35+
start = mid + 1
36+
else:
37+
if target <= nums[end] and target > nums[mid]:
38+
start = mid + 1
39+
else:
40+
end = mid - 1
41+
return -1

0 commit comments

Comments
 (0)