N刷33. Search in Rotated Sorted Array

这道老题思路应该很透彻了。一开始分nums[mid] == target和nums[mid]可能掉入两大段讨论:


N刷33. Search in Rotated Sorted Array_第1张图片
image.png

然后在两大段每一段里面又可以具体分析成两种情况:


N刷33. Search in Rotated Sorted Array_第2张图片
image.png

最后检查一下start 和end index的元素是不是target就可以

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;
        while (start + 1 < end){
            int mid = start + (end - start) / 2;
            if (nums[mid] == target){
                return mid;
            } else if (nums[mid] > nums[start]){
                if (target >= nums[start] && target <= nums[mid]){
                    end = mid;
                } else {
                    start = mid;
                }
            } else if (nums[mid] < nums[end]){
                if (target >= nums[mid] && target <= nums[end]){
                    start = mid;
                } else {
                    end = mid;
                }
            }
        }
        if (nums[start] == target){
            return start;
        } 
        if (nums[end] == target){
            return end;
        }
        return -1;
    }
}

你可能感兴趣的:(N刷33. Search in Rotated Sorted Array)