Created
October 17, 2017 14:30
-
-
Save cixuuz/436a7f6a61a0905be9c12287bfe8c58c to your computer and use it in GitHub Desktop.
[33. Search in Rotated Sorted Array] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution(object): | |
def search(self, nums, target): | |
""" | |
:type nums: List[int] | |
:type target: int | |
:rtype: int | |
""" | |
# corner case: input is None or empty list | |
if not nums: | |
return -1 | |
# binary search | |
left = 0 | |
right = len(nums) - 1 | |
while left <= right: | |
mid = left + (right - left) // 2 | |
if nums[mid] == target: | |
return mid | |
# sorted from left to mid | |
if nums[left] <= nums[mid]: | |
# target in left and mid | |
if target < nums[mid] and target >= nums[left]: | |
right = mid - 1 | |
else: | |
left = mid + 1 | |
# sorted from mid to right | |
if nums[mid] <= nums[right]: | |
if target > nums[mid] and target <= nums[right]: | |
left = mid + 1 | |
else: | |
right = mid - 1 | |
return -1 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment