LeetCode33. 搜索旋转排序数组

思路是:

  1. 先找到最小的值,这个值的位置就是旋转的地方。
  2. 然后判断target和nums[0]的大小,如果target大于,那么就找前 半段,如果不是就后半段进行二分查找。
  3. 题目链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array/
class Solution {
    int [] nums;
    int target;
    public int search(int[] nums, int target) {
        this.nums = nums;
        this.target = target;

        int n = nums.length;

        if (n == 0)
        return -1;
        if (n == 1)
        return this.nums[0] == target ? 0 : -1;

        int rotate_index = find_rotate_index(0, n - 1);

        // if target is the smallest element
        if (nums[rotate_index] == target)
        return rotate_index;
        // if array is not rotated, search in the entire array
        if (rotate_index == 0)
        return search(0, n - 1);
        if (target < nums[0])
        // search in the right side
        return search(rotate_index, n - 1);
        // search in the left side
        return search(0, rotate_index);
    }
    public int find_rotate_index(int left,int right){
        if(nums[left] < nums[right]){
            return 0;
        }
        while(left <= right){
            int pivot = (left + right) / 2;
            if(nums[pivot] > nums[pivot + 1]){
                return pivot + 1;
            }else{
                if(nums[pivot] < nums[left])
                    right = pivot -1;
                else
                    left = pivot + 1;  
            }
        }
        return 0;
    }
    public int search(int left, int right){
        while(left <= right){
            int pivot = (left +right) /2;
            if(nums[pivot] == target ){
                return pivot;
            }else{
                if(nums[pivot] < target){
                    left = pivot + 1;
                }else{
                    right = pivot -1;
                }
            }
        }
        return -1;
    }

}
作者:LeetCode
链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array/solution/sou-suo-xuan-zhuan-pai-xu-shu-zu-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值