[leetCode]Search in Rotated Sorted Array

问题1:

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

思路:使用二分查找,若中间数大于等于最左端数,那左半部分必定有序,否则右半部分有序,通过将目标数与有序部分的最大与最小数比较就可以判断目标数位于哪一部分。

    int search1(int A[], int n, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
		if(n == 0)
			return -1;

		int L = 0;
		int H = n - 1;
		int M = 0;
		while(L <= H)
		{
			M = L + (H - L)/2;
			if(target == A[M])
				return M;

			if(A[L] <= A[M])
			{
				if(target >= A[L] && target < A[M])
				{
					H = M -1;
				}
				else
					L = M + 1;
			}
			else
			{	
				if(target > A[M] && target <= A[H])
					L = M + 1;
				else
					H = M - 1;

			}
		}
		return -1;
        
    }


问题2:

同样是问题1, 只不过移位数组中出现了相同的数。是duplicated.

思路:

思路:二分查找,需要注意的是,若中间数字跟最左端数字相等时,去掉最左端的数字,然后递归查找。

bool search(int A[], int n, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
		if(n == 0)
			return false;

		int L = 0;
		int H = n - 1;
		int M = 0;
		while(L <= H)
		{
			M = L + (H - L)/2;
			if(target == A[M])
				return true;

			if(A[L] < A[M])
			{
				if(target >= A[L] && target < A[M])
				{
					H = M -1;
				}
				else
					L = M + 1;
			}
			else if(A[M] < A[L])
			{	
				if(target > A[M] && target <= A[H])
					L = M + 1;
				else
					H = M - 1;

			}
			else L ++;
		}
		return false;
        
    }




你可能感兴趣的:([leetCode]Search in Rotated Sorted Array)