leetcode81. Search in Rotated Sorted Array II

思路:先找到回旋点(右段起点)同154,再对左右两段分别进行二分搜索

Your runtime beats 100.00 % of java submissions.

class Solution {
    public boolean search(int[] nums, int target) {
    	if(nums.length==0){
    		return false;
    	}
        int low=0,high=nums.length-1;
        int middle;
        //low将保存最小值点即旋转点
    	while(nums[low]>=nums[high]){//仍是两段(> || =) || 只有一段(元素全相等)
    		middle=(low+high)/2;
    		if(nums[middle]==nums[low] && nums[middle]==nums[high]){//仍是两段无法在二分 || 只有一段元素全相等。顺序查找
    			while(low+1<=high && nums[low]<=nums[low+1]){
    				low++;
    			}
    			if(low!=high){//有下降
    				low=low+1;
    			}
    			break;
    		}
    		//经过if判断,到此必然仍为可分的两段
    		if(nums[middle]>=nums[low]){//nums[middle]>=nums[low]>=nums[high],不全取'=',则nums[middle]>nums[high],middle在左段
    			low=middle+1;
    		}else{
    			high=middle;
    		}
    	}
        int index=-1;
        if(target<=nums[nums.length-1]){//在右段找
        	index=binarySearch(nums, low, nums.length-1, target);
        }else{
        	index=binarySearch(nums, 0, low-1, target);//先右后左
        }
        return index==-1?false:true;
    }
    //在有序数组arr[start,end]中找target,返回其索引
    public int binarySearch(int[] arr,int start,int end,int target){
    	int middle;
    	while(start<=end){
    		middle=(start+end)/2;
    		if(arr[middle]==target){
    			return middle;
    		}else if(arr[middle]>target){
    			end=middle-1;
    		}else{
    			start=middle+1;
    		}
    	}
    	return -1;
    }
}

你可能感兴趣的:(leetcode,leetcode)