LeetCode 120 Search in Rotated Sorted Array

Suppose a sorted array 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.

分析:

虽然有序数组折了,但是二分的时候一定有一边是有序的,利用中间元素和右端点元素相比来判断哪一边是有序的。

A[mid] <= A[end], 说明,mid到end之间的元素一定是有序的,

反之,说明,start到mid之间的元素一定是有序的。

判断出来那边有序之后,先判断target是不是在有序的部分里,如果是,就在有序的部分里查找,不是的归为另一类。

public class Solution {
    public int search(int[] A, int target) {
        return search(A, target, 0, A.length-1);
    }
    public int search(int[] A, int target, int start, int end){
        if(start>end)
            return -1;
        int mid=(start+end)/2;
        if(target == A[mid])
            return mid;
        if(A[mid] >= A[end]){//左边有序
            if(target < A[mid] && target>=A[start])
                return search(A, target, start, mid-1);
            else
                return search(A, target, mid+1, end);
        }else{//右边有序
            if(target > A[mid] && target<=A[end])
                return search(A, target, mid+1, end);
            else
                return search(A, target, start, mid-1);
        }
    }
}


你可能感兴趣的:(LeetCode,in,search,so,rotated)