您的位置:首页 > 其它

LeetCode OJ 81 Search in Rotated Sorted Array II

2015-07-11 11:24 295 查看
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.

思路:假如有重复的元素后,需要在进行first和mid进行更为细致的划分。当first>mid时,显然前半段非顺序,则后半段必为顺序(可能包含重复);当first==mid时,则前半段必非顺序且包含重复元素,只需要将first不断++即可找到逆序区间;first<mid时,则前半部分为顺序区间。

代码如下

class Solution {
public:
bool search(vector<int>& nums, int target) {
int first=0;
int last=nums.size()-1;
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])
first=mid+1;
else
last=mid;
}
else
{
first++;
}
}
if(nums[last]==target)
return true;
else
return false;

}
};


运行时间:8ms

运行结果分析:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: