Need an algorithm for a special array (linear field)

余生长醉 提交于 2020-01-04 05:16:14

问题


I have an Array (linear field) with pre sorted numbers

 [1, 2, 3, 4, 5, 6],

but these arra y is shift to the right (k times),

now its

[5,6,1,2,3,4], k = 2

But I don´t know k. Only the array A.

Now I need an Algorithm to find the max in A (with runtime O(logn))

I think its something with binary search, can anyone help me??


回答1:


The question can be re-stated in terms of finding the "point of discontinuity", i.e the index of the 6, 1 spot in the array. You can do it iteratively using an approach similar to that of a binary search, like this:

Take an array A and two indexes, low and high, initially set to 0 and A.Length-1. The spot of discontinuity is between low and high.

Divide (low, high) in half. Call the midpoint mid. Compare A[low] to A[mid] and A[mid] to A[high]. If only one pair is ordered correctly, adjust the endpoint: if it's the low-mid pair that's ordered, assign low = mid, otherwise assign high = mid. If both intervals are ordered, the answer is A[high].

This runs in O(LogN) because each step reduces the size of the problem in half.




回答2:


You're correct that it's basically a binary search.

Pick the middle number. If that's smaller than the number at the left end (of the current partition) then the largest number is in the left partition. Otherwise, it's in the right partition.




回答3:


If you know what 'k' is, then you could either split the array and rebuild it, or you could reimplement a binary search algorithm that offsets by k.

For example,

int low = 0;
int high = array.length - 1;

while(low != high)
{
    int test = (low + high)/2;
    int testIndex = (test + k) % array.length;
    if (array[testIndex] < wanted)
        low = test;
    else if (array[testIndex] > wanted)
       high = test;
    else
       return testIndex;
 }

Or something like that. The testIndex variable is offset by 'k', but the search indexes (low, high, and test) don't know that.

PS., You will need to add more safety checks to this code (eg., 'wanted' not in array); I just wanted to show the index offset part.



来源:https://stackoverflow.com/questions/14243471/need-an-algorithm-for-a-special-array-linear-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!