您的位置:首页 > 其它

Leetcode 81. Search in Rotated Sorted Array II

2016-12-27 07:25 399 查看
/**
* similar with Search in Rotated Sorted Array,
* the difference is we need to take care of the case such as
* 1, 1, ..., 1, 1 here, 1 is the duplicate element.
* The algorithm discussed in the Search in Rotated Sorted Array should start at 2 in this case.
* Therefore, we 'remove' the duplicates at the beginning of the array, then apply Search in Rotated Sorted Array.
* Running time for the worst case should be o(n).
*/
public class Solution {
// find the index of the minimum
public int searchMin (int low, int[] nums) {
int high = nums.length-1, mid = 0;
while (low < high) {
mid = (low+high)/2;
if (nums[mid] > nums[high]) low = mid + 1;
else high = mid;
}
return low;
}

// binary search for sorted array
public boolean binarySearch (int[] nums, int low, int high, int target) {
int mid = 0;
while (low < high) {
mid = (low+high)/2;
if (nums[mid] < target) low = mid+1;
else high = mid;
}
return (nums[low] == target) ? true : false;
}

public boolean search(int[] nums, int target) {
int i=0, imin = 0;
// skip duplicates at the beginning of the array
if (nums[i] == nums[nums.length-1]) {
for (i=1; i<nums.length; i++)
if (nums[i-1] != nums[i]) break;
}
// cases such as [1], [1,1,1] arrays that only contain duplicates (*)
if (i == nums.length) return (nums[i-1] == target);

imin = searchMin(i, nums);
if (target <= nums[nums.length-1]) return binarySearch(nums, imin, nums.length-1, target);
return binarySearch(nums, 0, imin-1, target);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: