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

搜索旋转排序数组

【LeetCode-33】33. 搜索旋转排序数组_第1张图片
【LeetCode-33】33. 搜索旋转排序数组_第2张图片

修改的二分查找

注意:这道题的数组中没有重复数字

思路参考

class Solution {
    public int search(int[] nums, int target) {
        if(nums == null || nums.length == 0) {
            return -1;
        }
        int n = nums.length;
        if(n == 1) {
           return nums[0] == target ? 0 : -1;
        }
        int left = 0;
        int right = n - 1;
        
        while(left <= right) {
            int mid = left + (right - left) / 2;
            if(nums[mid] == target) {
                return mid;
            }
            //注意找出左/右中哪一部分有序
            
            //1.left-mid是有序的
            if(nums[0] <= nums[mid]) {
                if(nums[0] <= target && target < nums[mid]) {
                    //左边界有序且target在有序的左半边
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
                
            } else if(nums[0] > nums[mid]){
                //2. mid-right是有序的
                
                //target在有序的序列中
                if(nums[mid] < target && target <= nums[n - 1]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
        return -1;
    }
}
class Solution {
    public int search(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        int start = 0;
        int end = nums.length - 1;
        int mid;
        while (start <= end) {
            mid = start + (end - start) / 2;
            if (nums[mid] == target) {
                return mid;
            }
            //前半部分有序,注意此处用小于等于
            if (nums[start] <= nums[mid]) {
                //target在前半部分
                if (target >= nums[start] && target < nums[mid]) {
                    end = mid - 1;
                } else {
                    start = mid + 1;
                }
            } else {
                if (target <= nums[end] && target > nums[mid]) {
                    start = mid + 1;
                } else {
                    end = mid - 1;
                }
            }

        }
        return -1;

    }

}

同类型题目

注意该题的数组包含重复元素
81.搜索旋转排序数组 II

你可能感兴趣的:(LeetCode,校招笔试面试算法真题,搜索旋转排序数组,二分搜索,猿辅导面试)