AC answer based on "Search in Rotate Sorted Array" so two problems "consolidated" as one


  • 4
    B

    The only difference is the two "while" lines, so we don't have to remember/understand totally different solutions for these two series problems: "Search in Rotate Sorted Array" and "Search in Rotate Sorted Array II"

    public boolean search(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;
        
        while (start <= end) {
            int mid = start + (end - start) / 2;
            // System.out.format("start=%d,mid=%d,end=%d\n",start,mid,end);
            if (nums[mid] == target) return true;
            
            // need to handle: 1,3,1,1,1
            while (nums[start] == nums[mid] && start != mid) {
                start ++;
            }
            while (nums[mid] == nums[end] && mid != end) {
                end --;
            }
    
            // the following is the same as problem I
            if (nums[start] <= nums[mid]) {
                if (nums[start] <= target && target < nums[mid]) {
                    end = mid - 1;
                } else {
                    start = mid + 1;
                }
            } else {
                if (nums[mid] < target && target <= nums[end]) {
                    start = mid + 1;
                } else {
                    end = mid - 1;
                }
            }
        }
        
        return false;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.