【LeetCode】【HOT】33. 搜索旋转排序数组(二分查找)

【LeetCode】【HOT】33. 搜索旋转排序数组

文章目录

  • 【LeetCode】【HOT】33. 搜索旋转排序数组

【LeetCode】【HOT】33. 搜索旋转排序数组(二分查找)_第1张图片

package hot;

public class Solution33 {
    public static void main(String[] args) {
        int[] nums = {4,5,6,7,0,1,2};
        Solution33 solution = new Solution33();
        System.out.println(solution.method(nums, 0));
    }

    private int method(int[] nums, int target){
        int n = nums.length;
        if(n == 0) return -1;
        if(n == 1) return nums[0] == target ? nums[0] : -1;
        int l = 0;
        int r = n - 1;
        while(l <= r){
            int m = (l + r) / 2;
            if(nums[m] == target){
                return m;
            }
            if(nums[0] <= nums[m]){
                if(nums[0] <= target && target < nums[m]){
                    r = m - 1;
                }else{
                    l = m + 1;
                }
            }else{
                if(nums[m] < target && target <= nums[r]){
                    l = m + 1;
                }else{
                    r = m - 1;
                }
            }
        }
        return -1;
    }
}

//时间复杂度为 O(logn)
//空间复杂度为 O(1)

你可能感兴趣的:(LeetCode,LeetCode)