LeetCode Search in Rotated Sorted Array II

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.


较上个题只需少量改动,但是复杂度已经是O(N)了,所以应该直接用线性搜索。
class Solution {
public:
    bool search(int A[], int n, int target) {
        if(NULL == A || 0 == n)
        	return false;
		int left = 0, right = n-1, mid = 0;
		while(left <= right)
		{
			mid = left+(right-left)/2;
			if(A[mid] == target)
				return true;
			bool isLeft = true;
			for(int i = left; i <= mid; ++i)
				if(A[i] > A[mid])
				{
					isLeft = false;
					break;
				}
			if(isLeft)//left
			{
				if(A[left] <= target && target < A[mid])
					right = mid - 1;
				else
					left = mid + 1;

			}
			else//right
			{
				if(A[mid] < target && target <= A[right])
					left = mid + 1;
				else
					right = mid - 1;
			}
		}

		return false;
    }
};

线性搜索
class Solution {
public:
    bool search(int A[], int n, int target) {
        if(NULL == A || 0 == n)
        	return false;
		for(int i = 0; i < n; ++i)
			if(A[i] == target)
				return true;
		return false;
    }
};




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