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>[1,3,1,1,1], 3

Would this affect the run-time complexity? How and why? --run-time的最坏情况是O(n)了,因为特殊情况出现的时候需要额外处理,可能做线性搜索

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

//本题重点考查特殊情况:
//[1,3,1,1,1], 3
class Solution {
public:
	bool search(int A[], int n, int target) 
	{
		return biSearch(A, 0, n-1, target);
	}

	bool biSearch(int A[], int low, int up, int tar)
	{
		if (low > up) return false;

		int mid = low + ((up-low)>>1);
		if (A[mid] == tar) return true;

		if (A[low] < A[mid])
		{
			if (A[low] <= tar && tar < A[mid]) return biSearch(A, low, mid-1, tar);
			else return biSearch(A, mid+1, up, tar);

		}
		else if (A[low] > A[mid])
		{
			if (A[mid]<tar && tar<=A[up]) return biSearch(A, mid+1, up, tar);
			else return biSearch(A, low, mid-1, tar);
		}
		//本题主要特殊情况处理方法:
		else
		{
			int t = mid;
			while (low<t && A[t] == A[low]) t--;
			if (low == t) return biSearch(A, mid+1, up, tar);
			else return biSearch(A, low, t, tar);
		}
		return false;
	}
};


最坏情况 1/4 O(n);常熟项是1/4

//2014-2-13 update
	bool search(int A[], int n, int target) 
	{
		return biSearch(A, 0, n-1, target);
	}
	bool biSearch(int A[], int low, int up, int tar)
	{
		if (low > up) return false;
		int mid = low + ((up-low)>>1);
		
		if (tar < A[mid])//分情况的时候一定要注意:把所有可能的情况都考虑完。
		{
			if (A[low] <= tar || A[low] > A[mid]) return biSearch(A, low, mid-1, tar);
			else if (A[low] == A[up]) return biSearch(A, low+1, up-1, tar);
			else return biSearch(A, mid+1, up, tar);
		}
		else if (A[mid] < tar)
		{
			if (tar <= A[up] || A[mid] > A[up]) return biSearch(A, mid+1, up, tar);
			else if (A[low] == A[up]) return biSearch(A, low+1, up-1, tar);
			else return biSearch(A, low, mid-1, tar);
		}
		return true;
	}


本人研究结果的最优程序:有比我更快的欢迎指教! 出处:http://write.blog.csdn.net/postedit/17485739

最坏情况 2 O(lgn);提高了一个等级了。  本程序缺点:很容易出错。


//2014-2-13 update 最优程序 2O(lgn)最坏情况
	bool search(int A[], int n, int target) 
	{
		return biSearch(A, 0, n-1, target);
	}
	bool biSearch(int A[], int low, int up, int tar)
	{
		if (low > up) return false;
		int mid = low + ((up-low)>>1);
		if (A[mid] == tar) return true;

		if (A[low] < A[mid])
		{
			if (A[low] <= tar && tar < A[mid]) return biSearch(A, low, mid-1, tar);
			else return biSearch(A, mid+1, up, tar);
		}
		else if (A[low] > A[mid])
		{
			if (A[mid] < tar && tar <= A[up]) return biSearch(A, mid+1, up, tar);
			else return biSearch(A, low, mid-1, tar);
		}
		bool flag = biSearch(A, mid+1, up, tar);//不能是up-1,如:【3,1】找1;
		if (!flag) flag = biSearch(A, low+1, mid-1, tar);
		return flag;
	}
};



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