Programming

Leetcode-33. Search in Rotated Sorted Array

Leetcode-33. Search in Rotated Sorted Array

There is an integer array nums sorted in ascending order (with distinct values).

Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], …, nums[n-1], nums[0], nums[1], …, nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].

Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

Example 3:

Input: nums = [1], target = 0
Output: -1

<解題>

  1. 要在sorted array裡面找target,但數列有被旋轉過,所以我們必須知道哪邊是最小值,才可以去找到target: a. 先確認嘴小值指標left b. 把最小值left設為start,來找到他的區間,如[4,5,6,7,0,1,2]中,0的左側或右側 c. 找target

class Solution {
    public int search(int[] nums, int target) {
        if(nums.length == 0) return -1;

        int left = 0;
        int right = nums.length-1;

        //先確認最小值的指標left
        while(left<right){
            int midpoint = left + (right - left)/2;
            if(nums[midpoint] > nums[right]){
                left = midpoint + 1;
            } else {
                right = midpoint;
            }
        }
        //把最小值left設為start,來找到他的區間,如[4,5,6,7,0,1,2]中,0的左側或右側
        int start = left; //start變成最小值
        left = 0;
        right = nums.length-1;
   
        if(target >= nums[start] && target <= nums[right]){ //target在start和right之間(也就是0的右側)
            left = start;
        } else{
            right = start;
        }

        //找target
        while (left<=right){
            int midpoint = left + (right - left)/2;
            if(nums[midpoint] == target){
                return midpoint;
            } else if(nums[midpoint] > target){
                right = midpoint -1;
            } else {
                left = midpoint +1;
            }

        }
        return -1;
    }
}

Time: O(logN)

Space: O(1)