Leetcode 33 搜索旋转排序数组

Leetcode 33 搜索旋转排序数组_第1张图片

class Solution {
    //旋转数组从中间分开,总有一侧是有序的,一侧是无序的
    //只需要判断是否在有序区间就可以进行二分查找
    public int search(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while(left <= right){
            int mid = (left + right) / 2;
            if(target == nums[mid]) return mid;
            //如果左侧有序
            if(nums[left] <= nums[mid]){
                //如果target也在左侧
                if(nums[left] <= target && target < nums[mid]){
                    right = mid - 1;
                }
                //在右侧
                else{
                    left = mid + 1;
                }
            }
            else{
                if(target <= nums[right] && target > nums[mid]){
                    left = mid + 1;
                }
                else{
                    right = mid - 1;
                }
            }
        }
        return -1;
    }
}

你可能感兴趣的:(leetcode,算法,数据结构)