Algorithm-finding kth next element in an array

后端 未结 3 1730
别那么骄傲
别那么骄傲 2021-01-20 14:30

I couldn\'t solve a question can you please help?

For i=1 to i=n/2, if A[i]<=A[2i] and A[i]<=A[2i+1] A is called as a \"bst\" 

What\

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-20 15:01

    I can be done in O(klogk), and assuming k< - that's going to be pretty efficient comparing to alternatives.

    The idea is to maintain a min-heap, start from the head (id==0), which is the lowest element, and iteratively add all "new candidates" (which are for a given current lowest i - the "candidates" are 2i and 2i+1).

    Create a new empty min-heap, where each element contains a tupple (x,i) - x is the key in the array, and i is its index

    set i = 0, currIdx = 0
    heap.add((i,0))
    while currIdx < k:
    currIdx = currIdx + 1
       (x,i) = heap.popLowest()
       if i != 2i: //for i=2i=0, don't add it twice:
           heap.add((arr[2i],2i))
       heap.add((arr[2i+1],2i+1))
    return heap.getTop()
    

    Time complexity is O(klogk), each operation on the heap takes O(logN) (where N is its current size), and the heap grows to maximal size of N=k, so all operations on the heap is log(1) + log(2) + ... + log(k) = log((k)!), which is in O(klogk).

提交回复
热议问题