Search in Rotated Sorted Array I & II

By | August 10, 2016
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

leetcode 33, 81

Suppose a sorted array 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).

You are given a target value to search. If found in the array return its index, otherwise return -1.

What if duplicates are allowed?

Solution. I referred this nice solution.

rotatedarray

Compared to without duplicate, the version for with duplicate has a part of code to judge if nums[left] == nums[mid] == nums[rigt]. If so, then left++, right–.

One more thing we need to pay attention is that when we check the first type of shape, we need to check use >= for nums[mid] >= nums[left] instead of nums[mid] > nums[left].

public static boolean search(int[] nums, int target) {
    int left = 0, right = nums.length - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (target == nums[mid]) {
            return true;
        }
        if (nums[left] == nums[mid] && nums[mid] == nums[right]) {
            left++;
            right--;
        }
        else if (nums[mid] >= nums[left]) { // left side is longer
            if (target >= nums[left] && target < nums[mid]) {   // to left
                right = mid - 1;
            }
            else {
                left = mid + 1;
            }
        }
        else {  // right side is longer
            if (nums[mid] < target && target <= nums[right]) {  // to right
                left = mid + 1;
            }
            else {
                right = mid - 1;
            }
        }
    }
    return false;
}

Check my code on github i, ii.