1. 程式人生 > >33. Search in Rotated Sorted Array的C++解法

33. Search in Rotated Sorted Array的C++解法

看到時間複雜度要求是O(logn)所以首先想到的還是二分查詢,但是這個查詢不是完全有序的,而是兩段升序的。演算法需要找到規律判斷下一次搜尋應該在哪個區間。如果中間的數小於最右邊的數,則右半段是有序的,若中間數大於最右邊數,則左半段是有序的,我們只要在有序的半段裡用首尾兩個陣列來判斷目標值是否在這一區域內,這樣就可以確定保留哪半邊了。  

class Solution {
public:
	int search(vector<int> &A, int target) {
		int head = 0;
		int tail = A.size() - 1;
		int mid;
		while (head <= tail)
		{
			mid = (head + tail) / 2;
			if (A[mid] == target) return mid;
			if (target > A[mid])
			{
				if (A[mid] <= A[tail])
					if (target <= A[tail]) head = mid + 1;
					else tail = mid - 1;
				else head = mid + 1;
			}
			if (target < A[mid])
			{
				if (A[head] <= A[mid])
					if (target >= A[head]) tail = mid - 1;
					else head = mid + 1;
				else tail = mid - 1;
			}
		}
		return -1;
	}
};