您的位置:首页 > 编程语言 > C语言/C++

leetcode刷题系列C++-Search in Rotated Sorted Array II

2016-01-29 11:15 537 查看
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.

Subscribe to see which companies asked this questionclass Solution {
public:
bool search(vector<int>& nums, int target) {
int first = 0;
int last = nums.size();
int middle = 0;
while(first != last)
{
middle = first + (last - first) / 2;
if(nums[middle] == target)
{
return true;
}
if(nums[first] < nums[middle])
{
if(nums[first] <= target && target < nums[middle])
{
last = middle;
}
else
{
first = middle + 1;
}
}
else if(nums[first] > nums[middle])
{
if(nums[middle] < target && target <= nums[last - 1])
{
first = middle + 1;
}
else
{
last = middle;
}
}
else
{
first++;
}
}
return false;
}
};出现11131这种的时候
 会发现first和last是相等的  此时就无法来通过first last和middle来确定middle的区间了,因此这个地方只需要增加一个first++就可以了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: