48. Find the target value in the rotated ordered array

 

Title description

Given an ordered array that has been rotated, you don’t know how much the array has been rotated in advance
(for example, 0 1 2 4 5 6 7 may become 4 5 6 7 0 1 2).
Search for the given target value in the array , If it can be found in the array, return its index, otherwise return -1.
Assume that there are no duplicates in the array.

[3,2,1],1

Example 1

enter

[1],0

return value

-1

Example 2

enter
 

[3,2,1],1

return value

2

 

Idea : If the number in the middle is less than the rightmost number, the right half is in order. If the middle number is greater than the rightmost number, the left half is in order. We only need to use the first and last two in the ordered half. An array to determine whether the target value is in this area, so that you can determine which half to keep

Code implementation :

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

 

Guess you like

Origin blog.csdn.net/xiao__jia__jia/article/details/113528686