LeetCode33:搜索旋转排序数组

LeetCode33:搜索旋转排序数组_第1张图片

class Solution {
    public int search(int[] nums, int target) {
        if(nums.length == 0){
            return -1;
        }
        int left = 0;
        int right = nums.length - 1;
        while(left <=right){
            int mid = left + (right-left)/2;
            if(nums[mid] == target){
                return mid;
            }
            //前半段有序
            if(nums[mid] >= nums[left]){
                //target在前半段
                if(target < nums[mid] && target >= nums[left]){
                    right = mid -1;
                }
                else{
                    left = mid + 1;
                }

            }
            //后半段有序
            else {
                if(target > nums[mid] && target <= nums[right]){
                    left = mid + 1;
                }
                else{
                    right = mid - 1;
                }
            }
        }
        return -1;

    }
}

 

你可能感兴趣的:(LeetCode)