leetcode search rotated sorted array mid

topic link

Seeing this O(logN) complexity requirement, the dichotomy comes to mind in an instant.

The rotation mentioned in this question is actually the exchange of the left and right as a whole, which leads to the emergence of two increasing sequences. That is to say, when we binary search, there are two possibilities, one is that the selected part is an increasing sequence, and the other is that the selected part spans two increasing sequences.

We just need to process that part of the increasing sequence each time.

 

class Solution {
    public int search(int[] nums, int target) {
        return Search(nums, 0, nums.length - 1, target);
    }
    private static int Search(int[] nums, int low, int high, int target) {
        if(low > high) return -1;
        int mid = low + high >> 1;
        if(nums[mid] == target) return mid;
        if(nums[mid] < nums[high]) {
            if(nums[mid] < target && target <= nums[high])
                 return Search(nums, mid + 1, high, target);
            else return Search(nums, low, mid - 1, target);
        }
        else {
            if(nums[low] <= target && target < nums[mid])
                return Search(nums, low, mid - 1, target);
            else return Search(nums, mid + 1, high, target);
        }
    }
}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326637625&siteId=291194637