`

Leetcode - Search in Rotated Sorted Array II

 
阅读更多
[分析] 同Search in Rotated Sorted Array 的差别在于数组元素可能重复,遇到重复无法推断target所属范围时就一步步移动左边界直到左边界和中间元素不同或者相遇为止。联系Find Minimum in Rotated Sorted Array II进行理解。

public class Solution {
    public boolean search(int[] nums, int target) {
        if (nums == null || nums.length == 0)
            return false;
        int left = 0, right = nums.length - 1;
        int mid = 0;
        while (left <= right) {
            mid = left + (right - left) / 2;
            if (nums[mid] == target)
                return true;
            else if(nums[left] < nums[mid]) {
                if (nums[left] == target) 
                    return true;  
                else if (nums[left] < target && target < nums[mid])
                    right = mid - 1;
                else
                    left = mid + 1;
            } else if (nums[left] == nums[mid]) {
                left++;
            } else {
                if (nums[right] == target)
                    return true;
                else if (nums[mid] < target && target < nums[right])
                    left = mid + 1;
                else
                    right = mid - 1;
            }
        }
        return false;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics