Search in Rotated Sorted Array

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.

二分查找的推广,需要增加判断条件,为方便举例我们假设要找的数字为3,先用mid把数列分为两种情况,再讨论两种情况的子情况

mid = first+ ( end - first)/2;

if ( A[mid ] == target ) return mid;(找到终止)

if ( A[first] <=  A[mid])   (这个时候还得考虑两种情况,1 2 3 4 5 6 7 8 9 和 5 6 7 8 9 1 2 3 4)

{

if( A[first] < target && target < =A[mid])

{ end=mid ; }

else

{ first= mid+1; }

}

else   ./A[first] > A[mid]) (7 8 9 1 2 3 4 5 6  和  9 1 2 3 4 5 6 7 8)

{

if(A[mid] < target && target <=A[end-1])

{ first = mid+1 }

else

{ end = mid; }

}

class Solution {
public:
    int search(int A[], int n, int target) {
        int first=0;
        int end=n;
        while(first!=end)
        {
            int mid =first+ (end - first)/2;
            if(A[mid] == target) return mid;
            if(A[first] <= A[mid])
            {
                if(A[first] <= target && target<A[mid] )
                {
                    end = mid;
                }
                else
                {
                    first = mid+1;
                }
            }
            else
            {
                if(A[mid] < target && target <= A[end-1] )
                {
                    first = mid+1;
                }
                else
                {
                    end = mid;
                }
                
            }
        }
        return -1;
    }
};


你可能感兴趣的:(Search in Rotated Sorted Array)