Search in Rotated Sorted Array II
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6]
might become [2,5,6,0,0,1,2]
).
You are given a target value to search. If found in the array return true
, otherwise return false
.
Example 1:
Input: nums = [2,5,6,0,0,1,2]
, target = 0
Output: true
Example 2:
Input: nums = [2,5,6,0,0,1,2]
, target = 3
Output: false
Follow up:
nums
may contain duplicates.class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
l = 0
r = len(nums) -1
return self.bin_search(nums, target, l, r)
def bin_search(self, nums, target, l, r):
m = (l+r)//2
if l > r:
return False
if nums[m] == target or nums[r] == target or nums[l] == target :
return True
else:
if nums[m] < nums[r]:
if nums[m] < target and target < nums[r]:
return self.bin_search(nums,target, m+1, r-1)
else:
return self.bin_search(nums,target, l+1, m-1)
elif nums[m] > nums[r]:
if nums[m] >target and target > nums[l]:
return self.bin_search(nums, target, l+1, m-1)
else:
return self.bin_search(nums, target, m+1, r-1)
else:
k = m
while m <= r:
if nums[m] == nums[r]:
m += 1
else:
if nums[m] == target:
return True
else:
return self.bin_search(nums,target,m+1,r-1)
return self.bin_search(nums, target, l+1, k-1)
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
迭代
l = 0
r = len(nums)-1
while(l <= r):
m = (l+r)//2
if nums[m] == target or nums[r] == target or nums[l] == target :
return True
else:
if nums[m] < nums[r]:
if target nums[m]:
l = m+1
else:
r = m -1
elif nums[m] > nums[r]:
if target nums[l]:
r = m-1
else:
l = m+1
else:
k = m
while m <= r:
if nums[m] == nums[r]:
m = m+1
else:
if target == nums[m]:
return True
else:
if target < nums[r] and target >= nums[m]:
l = m
break
else:
r = k - 1
break
r = k - 1
return False
Search in Rotated Sorted Array |
不同的是,数组中的元素可以重复,这样就多了一种情况的判断,即nums[mid] == nums[right]
这样会有两种情况:(mid,right)元素全相同,或者存在不同,若是前者,则在(left,mid)区间搜索;
若为后者,则需要在(mid,right)搜索(此时(left, mid)全为相同元素,肯定不为target)。
Search in Rotated Sorted Array |