題目:
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:
This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
Would this affect the run-time complexity? How and why?
解法:
是LeetCode 刷題記錄 33.Search in Rotated Sorted Array
的升級版
應用其中的解法1
解法1的核心思想是中間值小於最右的值,則右半段有序,如果大於最右的值,則左半段有序,然後再進行二分查找
但是該解法建立在沒有重複的元素,該題中有重複元素,所以會出現中間值與最右的值相等的時候
就會出現來面兩種情況,[3 1 1] 和 [1 1 3 1],對於這兩種情況中間值等於最右值時,目標值3既可以在左邊又可以在右邊,那怎麼辦麼,對於這種情況其實處理非常簡單,只要把最右值向左一位即可繼續循環,也可以最左值向右一位即可繼續循環
c++:
class Solution {
public:
bool search(vector<int>& nums, int target) {
int lo = 0;
int hi = nums.size() - 1;
while(lo <= hi){
int mid = lo + (hi - lo) / 2;
if(nums[mid] == target) return true;
if(nums[mid] < nums[hi]){
if(target > nums[mid] && target <= nums[hi]) lo = mid + 1;
else hi = mid -1;
} else if(nums[mid] > nums[hi]){
if(target >= nums[lo] && target < nums[mid]) hi = mid - 1;
else lo = mid + 1;
}else hi--;
}
return false;
}
};
java
class Solution {
public boolean search(int[] nums, int target) {
int lo = 0;
int hi = nums.length - 1;
while(lo <= hi){
int mid = lo + (hi - lo) / 2;
if(nums[mid] == target) return true;
if(nums[mid] < nums[hi]){
if(target > nums[mid] && target <= nums[hi]) lo = mid + 1;
else hi = mid -1;
} else if(nums[mid] > nums[hi]) {
if(target >= nums[lo] && target < nums[mid]) hi = mid - 1;
else lo = mid + 1;
} else {
hi--;
}
}
return false;
}
}
python:
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
lo = 0
hi = len(nums) - 1
while lo <= hi:
mid = lo + (hi - lo) / 2
if nums[mid] == target: return True
if nums[mid] < nums[hi]:
if target > nums[mid] and target <= nums[hi]: lo = mid + 1
else: hi = mid -1
elif nums[mid] > nums[hi]:
if target >= nums[lo] and target < nums[mid]: hi = mid - 1
else: lo = mid + 1
else:
hi -= 1
return False