Leetcode 81 Search in Rotated Sorted Array II
2016-09-23 21:28
246 查看
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.
在循环错位的有序数组中进行搜索,与33题类似
http://blog.csdn.net/accepthjp/article/details/52440406
不同的是元素可能重复,
当遇到等于的时候,只能一个个地缩小区间,而不能以log复杂度减小,所以在最坏情况下,效率会退化为O(n).
class Solution {
public:
bool search(vector<int>& nums, int target) {
int l=0,r=nums.size()-1;
while(l<=r)
{
int mid=(l+r)>>1;
if(nums[mid]==target) return true;
if(nums[mid]<nums[l])
{
if(target<nums[l] && target>nums[mid])
l=mid+1;
else
r=mid-1;
}
else if(nums[mid]>nums[l])
{
if(target>=nums[l] && target<nums[mid])
r=mid-1;
else
l=mid+1;
}
else
l++; //mid和l值相等,无法获知mid的位置
}
return false;
}
};
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.
在循环错位的有序数组中进行搜索,与33题类似
http://blog.csdn.net/accepthjp/article/details/52440406
不同的是元素可能重复,
当遇到等于的时候,只能一个个地缩小区间,而不能以log复杂度减小,所以在最坏情况下,效率会退化为O(n).
class Solution {
public:
bool search(vector<int>& nums, int target) {
int l=0,r=nums.size()-1;
while(l<=r)
{
int mid=(l+r)>>1;
if(nums[mid]==target) return true;
if(nums[mid]<nums[l])
{
if(target<nums[l] && target>nums[mid])
l=mid+1;
else
r=mid-1;
}
else if(nums[mid]>nums[l])
{
if(target>=nums[l] && target<nums[mid])
r=mid-1;
else
l=mid+1;
}
else
l++; //mid和l值相等,无法获知mid的位置
}
return false;
}
};
相关文章推荐
- [Leetcode] 81. Search in Rotated Sorted Array II
- LeetCode 81. Search in Rotated Sorted Array II
- [Leetcode 81, Medium] Search in Rotated Sorted Array II
- 【LeetCode】81. Search in Rotated Sorted Array II (2 solutions)
- leetcode 81:Search in Rotated Sorted Array II
- 81. Search in Rotated Sorted Array II Leetcode Python
- 【LEETCODE】81-Search in Rotated Sorted Array II [Python]
- leetcode 81 : Search in Rotated Sorted Array II
- leetCode 81.Search in Rotated Sorted Array II (旋转数组的搜索II) 解题思路和方法
- LeetCode 81 Search in Rotated Sorted Array II
- leetcode[81]Search in Rotated Sorted Array II
- LeetCode(33)(81) Search in Rotated Sorted Array I II
- leetcode_81——Search in Rotated Sorted Array II(二分查找)
- LeetCode81——Search in Rotated Sorted Array II
- [LeetCode]81 Search in Rotated Sorted Array II
- [leetcode] 81.Search in Rotated Sorted Array II
- leetcode || 81、Search in Rotated Sorted Array II
- [leetcode-81]Search in Rotated Sorted Array II(C)
- leetcode 81 :Search in Rotated Sorted Array II
- Leetcode 81. Search in Rotated Sorted Array II