33. Search in Rotated Sorted Array

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e.,[0,1,2,4,5,6,7]might become[4,5,6,7,0,1,2]).數組

You are given a target value to search. If found in the array return its index, otherwise return-1.code

You may assume no duplicate exists in the array.get

Your algorithm's runtime complexity must be in the order of _O_(log _n_).it

Example 1:搜索

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

Example 2:sort

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

屬於有序數組的搜索,用二分搜索就好di

public int search(int[] nums, int target) {
        int offset=0;
        for(int i=1;i<nums.length;i++){
            if(nums[i-1]>nums[i]){
                offset=i;
                break;
            }
        }
        int left=0;
        int right=nums.length-1;
        while(right>=left){
            int mid=(right+left)/2;
            int index=mid+offset;
            if(index>=nums.length) index-=nums.length;
            if(nums[index]==target) return index;
            else if(nums[index]<target) {
                left=mid+1;
            }else{
                right=mid-1;
            }
        }
        return -1;
}
相關文章
相關標籤/搜索