問題:用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;
}