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

Leetcode 81. Search in Rotated Sorted Array II (Medium) (cpp)

2016-07-12 11:58 393 查看
Leetcode 81. Search in Rotated Sorted Array II (Medium) (cpp)

Tag: Array, Binary Search

Difficulty: Medium

/*

81. Search in Rotated Sorted Array II (Medium)

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.

*/
class Solution {
public:
bool search(vector<int>& nums, int target) {
int first = 0, last = nums.size() - 1;
while (first != last) {
int mid = first + (last - first) / 2;
if (nums[mid] == target) {
return true;
}
else if (nums[first] < nums[mid]) {
if (nums[first] <= target && target < nums[mid]) {
last = mid - 1;
}
else {
first = mid + 1;
}
}
else if (nums[first] > nums[mid]) {
if (nums[mid] < target && target <= nums[last]) {
first = mid + 1;
}
else {
last = mid -1;
}
}
else {
first++;
}
}
if (nums[first] == target) {
return true;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: