[LeetCode] Search in Rotated Sorted Array

题目链接

int search(int A[], int n, int target) {
	int beg = 0, end = n-1;
	while(beg <= end)
	{
		int mid = (beg+end)/2;
		if(A[beg] <= A[end])
		{
			if(target < A[mid])
			{
				end = mid - 1;
			}
			else if(target > A[mid])
			{
				beg = mid + 1;
			}
			else
			{
				return mid;
			}
		}
		else
		{
			if(target > A[beg])
			{
				if(A[mid] < A[beg] || A[mid] > target)
				{
					end = mid - 1;
				}             
				else if(A[mid] < target)
				{
					beg = mid + 1;
				}
				else
				{
					return mid;
				}
			}
			else if(target == A[beg])
			{
				return beg;
			}
			else if(target < A[end])
			{
				if(A[mid] > A[end] || A[mid] < target)
				{
					beg = mid + 1;
				}
				else if(A[mid] > target)
				{
					end = mid - 1;
				}
				else
				{
					return mid;
				}
			}
			else if(target == A[end])
			{
				return end;
			}
			else
			{
				return -1;
			}
		}
	}
	return -1;
}


你可能感兴趣的:(LeetCode,刷题)