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++就可以了
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++就可以了
相关文章推荐
- socket编程之C语言一个简单监听程序
- c++随机数
- c++ 基类设计 需要注意的几点
- C语言程序员必读的5本书
- const和static的用法
- Notepad++搭配MinGW编译运行C,C++程序
- Notepad++配合MinGW直接编译运行C/C++代码的窍门
- Boost 学习之算法篇 partition_point
- 我不知道的C++
- C++文件读写详解(ofstream,ifstream,fstream)
- c语言:存款利息计算,1000元,存5年,求五种方案存款五年后的本息和
- c语言:我国国民生产总值的年增长率为10%,10年后国民生产总值与现在相比增长多少
- c语言:浪漫的putchar(),用数字向女朋友表白吧(ps:单身汪勿入)
- POJ3026 - Borg Maze [MST]
- C/C++区别
- 学习C字符串表示和字符串I/O(CprimerPlus11.1)的心得
- Effective C++: static_cast, const_cast
- C++复习五
- 减少C++代码编译时间的方法
- C/C++log日志库比较