Search in Rotated Sorted Array I & II
LeetCode 33 & 81
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low = 0
high = len(nums)-1
while low <= high:
mid = (high + low) //2
if nums[mid] == target:
return mid
while mid < high and nums[mid] == nums[high]:
high = high - 1
# [1, 2, 3, |4| ..... 0]
# [4, 4, 4, |4| ..... 0]
if nums[mid] > nums[high]:
#正常排序
if nums[low] <= target <= nums[mid]:
high = mid -1
else:
low = mid + 1
else:
# nums[mid]< nums[high]
# [7 ........|3|, 4, 5, 6]
if nums[mid] < target <= nums[high] :
low = mid + 1
else:
high = mid - 1
return -1Follow up
duplicates
return the first position of target in the array
Last updated