您的位置:首页 > 其它

[leetcode] 81. Search in Rotated Sorted Array II

2016-08-19 07:50 435 查看
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.

解法一:

当nuts[mid] == nums[right]的时候,right向左移动一位。其他的和Search in Rotated Sorted Array问题中没有duplicate的代码类似。

class Solution {
public:
bool search(vector<int>& nums, int target) {
if(nums.empty()) return 0;
int left = 0, right = nums.size()-1;

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