您的位置:首页 > 其它

81. Search in Rotated Sorted Array II

2017-02-17 08:48 260 查看
Follow up for "Search in Rotated Sorted Array":

What if duplicates are allowed?
Would this affect the run-time complexity? How and why?

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., 
0 1 2 4 5 6 7
 might become 
4
5 6 7 0 1 2
).

Write a function to determine if a given target is in the array.

The array may contain duplicates.
在rotated的数组里查找目标值,数组包含重复元素,这时分三种情况来判断,详见代码:

public boolean search(int[] nums, int target) {
int start = 0, end = nums.length - 1, mid = -1;
while(start <= end) {
mid = (start + end) / 2;
if (nums[mid] == target) {
return true;
}
//If we know for sure right side is sorted or left side is unsorted
if (nums[mid] < nums[end] || nums[mid] < nums[start]) {
if (target > nums[mid] && target <= nums[end]) {
start = mid + 1;
} else {
end = mid - 1;
}
//If we know for sure left side is sorted or right side is unsorted
} else if (nums[mid] > nums[start] || nums[mid] > nums[end]) {
if (target < nums[mid] && target >= nums[start]) {
end = mid - 1;
} else {
start = mid + 1;
}
//If we get here, that means nums[start] == nums[mid] == nums[end], then shifting out
//any of the two sides won't change the result but can help remove duplicate from
//consideration, here we just use end-- but left++ works too
} else {
end--;
}
}

return false;
}

这种方法需要检验两端,下面的方法不需要检验两端:

public boolean search(int[] nums, int target) {
int start = 0, end = nums.length - 1;

//check each num so we will check start == end
//We always get a sorted part and a half part
//we can check sorted part to decide where to go next
while(start <= end){
int mid = start + (end - start)/2;
if(nums[mid] == target) return true;

//if left part is sorted
if(nums[start] < nums[mid]){
if(target < nums[start] || target > nums[mid]){
//target is in rotated part
start = mid + 1;
}else{
end = mid - 1;
}
}else if(nums[start] > nums[mid]){
//right part is sorted

//target is in rotated part
if(target < nums[mid] || target > nums[end]){
end = mid -1;
}else{
start = mid + 1;
}
}else{
//duplicates, we know nums[mid] != target, so nums[start] != target
//based on current information, we can only move left pointer to skip one cell
//thus in the worest case, we would have target: 2, and array like 11111111, then
//the running time would be O(n)
start ++;
}
}

return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: