您的位置:首页 > 其它

[Leetcode] Search in Rotated Sorted Array II

2016-09-22 14:38 246 查看
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.

public class Solution {
public boolean search(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
while(start <= end) {
int mid = (start + end) / 2;
if(nums[mid] == target) {
return true;
}
else if(nums[start] < nums[mid]) {
if(target > nums[mid]) {
start = mid +1;
}
else if(target < nums[mid] && target >= nums[start]) {
end = mid -1;
}
else if(target < nums[mid] && target < nums[start]){
start = mid + 1;
}
}
else if(nums[start] > nums[mid]) {
if(target < nums[mid]) {
end = mid - 1;
}
else if(target > nums[mid] && target > nums[end]) {
end = mid - 1;
}
else if(target > nums[mid] && target <= nums[end]) {
start = mid + 1;
}
}
// when nums[start] == nums[mid], it can either be because pivot is on the right of mid or because of duplicates
else {
start++;
}
}
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: