首页 > 代码库 > [leetcode]Search in Rotated Sorted Array II

[leetcode]Search in Rotated Sorted Array II

问题描述:

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.


"Search in Rotated Sorted Array" can be seen here

基本思路:

与"Search in Rotated Sorted Array" 类似,只对返回值做少许修改即可。具体参见《Search in Rotated Sorted Array》


代码:

    bool search(int A[], int n, int target) {  //C++
        if(n < 0)
            return false;
        if(n == 1)
        { 
            if(A[0] == target)
                return true;
            else return false;
        }
        
        if(A[0] == target)
            return true;

            
        for(int i = 1; i < n; i++)
        {
            if(A[i] < A[i-1])
            {
                if(A[i] > target || A[i-1] < target || target > A[n-1])
                return false;
            }
            if(A[i] == target )
                return true;
        }
        return false;
    
    }


[leetcode]Search in Rotated Sorted Array II