Algorithm-finding kth next element in an array

后端 未结 3 1729
别那么骄傲
别那么骄傲 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 14:51

    First, you mean "heap", not "bst" (the data structure you described is necessarily a heap and is not necessarily a bst).

    Second, it's not at all obvious that this problem is solvable in O(k) time -- it was not until 1992 that Frederickson gave an O(k)-time algorithm for this. I haven't read this paper all the way through, but it's 18 pages of intricate technical argument, and I'm flabbergasted that Olympiad organisers would expect students to essentially come up with it from scratch! (Or perhaps they expect them to already be familiar with the algorithm -- in which case I would say that (a) it's still asking quite a lot, and (b) it's not a very good question.)

    0 讨论(0)
  • 2021-01-20 14:52

    There are two methods:

    1. O(k ln(n)) time complexity.
    2. O(k ln(k)) time complexity + O(K) space complexity.
    0 讨论(0)
  • 2021-01-20 15:01

    I can be done in O(klogk), and assuming k<<n - 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).

    0 讨论(0)
提交回复
热议问题