线性表-Search in Rotated Sorted Arr
2018-10-16 本文已影响85人
wenyilab
描述
Follow up for ”Search in Rotated Sorted Array”: What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
分析
此题允许重复元素,若按上题解法中A[m] >= A[l],那么[l,m]为递增序列的假设就不成立了,如[2,3,2,2,2]。
如果A[m] >= A[l]不能确定递增,那么就进行拆分成两个条件:
若A[m] > A[l],则区间[l,m]一定递增
若A[m] == A[l],那么就l++,将重复元素略过。
代码实现 c++
class solution{
pubic:
bool search(const vector<int>& nums,int target){
int first = 0,last = nums.size();
while(first != last){
const int mid = first + (last - first) / 2;
if (nums[mid] == target)
return true;
if (nums[first] < nums[mid]){
// 注意此处有等于号,表明在闭区间内
if(nums[first] <= target && target < nums[mid])
last = mid;
else
first = mid + 1;
} else if(nums[first] > nums[mid]){
if(nums[mid] < target && target <= nums[last - 1])
first = mid + 1;
else
last = mid;
} else
//跳过重复元素
first ++;
}
return false;
}
};
代码实现 python
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
if not nums:
return False
start, end = 0, len(nums) - 1
while start + 1 < end:
mid = int(start + (end - start) / 2)
if nums[mid] == target:
return True
elif nums[mid] > nums[start]:
if target >= nums[start] and target <= nums[mid]:
end = mid
else:
start = mid
elif nums[mid] < nums[start]:
if target >= nums[mid] and target <= nums[end]:
start = mid
else:
end = mid
else:
start += 1
if nums[start] == target:
return True
if nums[end] == target:
return True
return False