Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Created October 17, 2017 14:30
Show Gist options
  • Save cixuuz/436a7f6a61a0905be9c12287bfe8c58c to your computer and use it in GitHub Desktop.
Save cixuuz/436a7f6a61a0905be9c12287bfe8c58c to your computer and use it in GitHub Desktop.
[33. Search in Rotated Sorted Array] #leetcode
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