搜索旋转排序数组 (Search in Rotated Sorted Array)

 

思路:

// @Title: 搜索旋转排序数组 (Search in Rotated Sorted Array)
// @Author: qisiii
// @Date: 2024-04-25 23:32:47
// @Runtime: 0 ms
// @Memory: 40.9 MB
// @comment: 
// @flag: 
class Solution {
    public int search(int[] nums, int target) {
        return binarySearch(nums,0,nums.length-1,target);
    }

    private int binarySearch(int[] nums,int left,int right,int target){
        if(left>right){
            return -1;
        }
        int mid=left+(right-left)/2;
        int l=left,r=right;
        if(nums[mid]==target){
            return mid;
        }
        if(nums[left]<=nums[mid]){
            if(nums[left]<=target&&target<nums[mid]){
                return binarySearch(nums,left,mid-1,target);
            }else{
                return binarySearch(nums,mid+1,right,target);
            }
        }else{
            if(nums[mid]<target&&target<=nums[right]){
                return binarySearch(nums,mid+1,right,target);
            }else{
                return binarySearch(nums,left,mid-1,target);
            }
        }
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18