Search in Rotated Sorted Array II
medium 原题链接:https://leetcode.com/problems/search-in-rotated-sorted-array-ii/
Search in Rotated Sorted Array II
原题链接:https://leetcode.com/problems/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 returnfalse
.
例子
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
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?
解法一
class Solution {
public:
bool search(vector<int>& nums, int target) {
int i=0;
while(i<nums.size()){
if(nums[i]==target)return true;
i++;
}
return false;
}
};
解法二
二分查找法
class Solution {
public:
bool search(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
//skip duplicate one
first++;
}
return false;
}
};
分析:T=O(n), S=O(1)
如果nums里用重复的数出现是否会增加时间复杂度?
总结
最后更新于
这有帮助吗?