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.

You may assume no duplicate exists in the array.

思路:二分搜索,只不过因为有转折,所以判断那一部分是正常的顺序,那一部分有转折。如果target在正常部分,就正常搜索。

注意边界的判断,比如[1,3] target = 3,[1,2],target = 0,[1] target = 1这种。

class Solution {
    public int search(int[] nums, int target) {
        if(nums.length==0) return -1;
        int s = 0;
        int e = nums.length-1;
        int m;
        while(s<=e){
            m = (s+e)/2;
            System.out.println("nums[m]="+nums[m]+";m="+m);
            if(nums[m]==target) {
                return m;
            }
                //System.out.println("m="+m+";s="+s+";e="+e);
                if(nums[s]<=nums[m]){//s到m之间正常有序,如果target在此区间内,正常二分,等号的目的是考虑[3,1]target=1的情况
                    if(nums[m]>target&&target>=nums[s]){
                        e = m-1;
                    }else{
                        s = m+1;
                    }                       
                }else{//m到e之间正常有序,如果target在此区间内,正常二分
                    if(nums[e]>=target&&target>nums[m]){
                        s = m+1;
                    }else{
                        e = m-1;
                    }    

                        
            }            
        }
        
        return -1;
    }
}
注意,这几个边界条件我是硬试出来的
。。。晕了



你可能感兴趣的:(Leetcode)