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
Noted that: The array may contain dumplicated value, so this is different to Leet Code 33. Search in Rotated Sorted Array
In the rotated array, if array[mid] == array[right], the position area of mid is not certain. For example, 4 4 5 4. So this condition should be disscussed.
Firstly, if array[target] != array[left] and array[target] != array[right], let left=left+1, right=right-1, Search the array in the next iteration.
Implemention is displayed in the following.
1 Iteration
class Solution:
def search(self, nums: 'List[int]', target: 'int') -> 'bool':
l, r = 0, len(nums) - 1
while l <= r:
mid = (l + r) // 2
if nums[mid] == target:
return True
if nums[mid] < nums[r]:
if target >= nums[mid] and target <= nums[r]:
l = mid + 1
else:
r = mid - 1
elif nums[mid] > nums[r]:
if target >= nums[l] and target <= nums[mid]:
r = mid-1
else:
l = mid + 1
else:
if nums[l] == target or nums[r] == target:
return True
else:
l += 1
r -= 1
return False
2 Recursion
class Solution:
def search(self, nums: 'List[int]', target: 'int') -> 'bool':
def recursion(nums, l, r):
if l <= r:
mid = (l + r) // 2
if nums[mid] == target:
return True
if nums[mid] < nums[r]:
if target >= nums[mid] and target <= nums[r]:
l = mid + 1
else:
r = mid - 1
elif nums[mid] > nums[r]:
if target >= nums[l] and target <= nums[mid]:
r = mid-1
else:
l = mid + 1
else:
if nums[l] == target or nums[r] == target:
return True
else:
l += 1
r -= 1
return recursion(nums, l, r)
else:
return False
return recursion(nums, 0, len(nums) - 1)