Leetcode 81. Search in Rotated Sorted Array II

来源:互联网 发布:淘宝如何添加全屏代码 编辑:程序博客网 时间:2024/06/07 20:17
/** * 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);    }}

0 0
原创粉丝点击