您的位置:首页 > 其它

LeetCode 81. Search in Rotated Sorted Array II

2016-04-24 10:53 393 查看
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.

Worst Time Complexity would be O(N).... for example: whole array is [4, 4, 4, 4, 4.....4] then the target is 3.

#include <vector>
#include <iostream>
using namespace std;

bool search(vector<int>& nums, int target) {
if(nums.size() == 0) return false;
int low = 0;
int high = nums.size() - 1;
while(low <= high) {
int mid = low + (high - low) / 2;
if(nums[mid] == target) return true;
if(nums[mid] < nums[high]) {
if(target <= nums[high] && target > nums[mid]) {
low = mid + 1;
} else high = mid - 1;

} else if(nums[mid] > nums[high]) {
if(target >= nums[low] && target < nums[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
} else { high--;}
}
return false;
}

// duplicates in rotated sorted array.
// For example: 4, 4, 5, 6, 1, 2, 3, 4, target is 3.
int main(void) {
vector<int> nums{4, 4, 5, 6, 1, 2, 3, 4};
int target = 2;
bool found = search(nums, target);
cout << found << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: