【Leetcode】Search in Rotated Sorted Array

在旋转的无重复的排序数组中查找某个数,要求时间复杂度O(logN)

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.

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

 

class Solution

{

public:

	int search(int A[], int n, int target) 

	{

		return search(A,0,n-1,target);

	}



	int search(int *ary, int start, int end, int target)

	{

		if (start > end) return -1;



		int mid = start + ((end-start)>>1);

		int number0 = ary[start];

		int number = ary[mid];

		int number1 = ary[end];



		if (number == target) 

			return mid;



		if (number >= number0)

		{

			if(target < number0 || target > number)

				return search(ary,mid+1,end,target);

			else

				return search(ary,start,mid-1,target);

		}

		

		// number < number0

		if (target > number1 || target < number)

			return search(ary,start,mid-1,target);

		

		return search(ary,mid+1,end,target);

	}

};


 

 

你可能感兴趣的:(LeetCode)