问题:用C++代码实现函数 FindSortedArrayRotation。该函数接受一个整数数组和数组的长度。这个整数数组本来是有序的(升序),但被轮转了X位置(对给定的整数X (0 <= X <= (arrayLength - 1)),数组的每个元素向前移动X位置,也就是array[i]移动到array[(i+X)%arrayLength]。请实现FindSortedArrayRotation,找出X。要求时间必须小于O(n)
参考代码:
以下为引用的内容:
int FindSortedArrayRotation(int *array, int arrayLength)
{
// Insert your implementation here
/*
After rotation the array was divided into 2 parts: array[0…x-1] and array[x…arrayLength-1]. And each part is sorted in ascending order. But array[x-1]>array[x]. This is a turn corner. My idea is use binary_search algorithm to find the turn corner.
Running time is O(log(2)).
*/
int left = 0;
int right = arrayLength – 1;
if(array[left]<= array[right]) return 0;
while(left<=right)
{
int middle = (left+right)/2;
if(array[middle -1] > array[middle]) return middle;
if(array[middle] > array[right]) left = middle + 1;
else right = middle -1;
}
return -1;
}
|