【leetcode】Search in Rotated Sorted Array II

class Solution {
public:
    bool search(int A[], int n, int target) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int sta=0,end=n-1;
        while(sta<=end)//注意等號
        {
            int mid=(sta+end)/2;
            if(A[sta]<target&&target<A[mid])//二分
                end=mid-1;
            else if(A[mid]<target&&target<A[end])//二分
                    sta=mid+1;
            else//不能明確縮小範圍時,線性
            {
                if(A[sta]!=target)
                    sta++;
                else
                    return true;
                if(A[end]!=target)
                    end--;
                else 
                    return true;
            }
        }
        return false;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章