[LeetCode 81] Search in Rotated Sorted Array II (Medium)

SOLUTION

  1. 与1不同的是,array中包含了重复得元素,那么就需要处理比如下面的情况
3 1 2 3 3 3 3     target = 1
3 3 3 3 1 2 3     target = 1

2.因此需要处理nums[middle] == nums [end] != targetnums[middle] == nums [start] != target这两种情况。
这两种情况下,无法去掉一半的数组,只能end -- 或/和 start++。一个个缩小范围。

  1. 对时间复杂度的影响就是,worst case: O(n)
class Solution {
    public boolean search(int[] nums, int target) {
        if (nums == null || nums.length == 0)
            return false;
        
        int start = 0;
        int end = nums.length - 1;
        
        while (start + 1 < end) {
            int middle = start + (end - start) / 2;
            if (nums [middle] == target)
                return true;
            
            // start - middle: ascending
            if (nums [start] < nums [middle]) {
                if (target <= nums [middle] && target >= nums [start] ) {
                    end = middle;
                } else {
                    start = middle;
                }
            } else if (nums [middle] < nums [end]) { // middle - end: ascending 
                if (target >= nums [middle] && target <= nums [end]) {
                    start = middle;
                } else {
                    end = middle;
                }
            } else { //唯一与 1不同的地方就是需要处理 nums [start] == nums [middle] == nums [end] != target的情况,此时无法去掉半边,只能一个个去掉
                if (nums [middle] == nums [end] && nums [end] != target) {
                    end --;
                }
                
                if (nums [start] == nums [middle] && nums [start] != target) {
                    start ++;
                }
            }
        }
        
        if (nums [start] == target || nums [end] == target)
            return true;
                
        return false;
    }
}

你可能感兴趣的:([LeetCode 81] Search in Rotated Sorted Array II (Medium))