Find median value from a growing set

后端 未结 8 1592
灰色年华
灰色年华 2020-12-04 10:03

I came across an interesting algorithm question in an interview. I gave my answer but not sure whether there is any better idea. So I welcome everyone to write something abo

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 10:35

    Although wrang-wrang already answered, I wish to describe a modification of your binary search tree method that is sub-linear.

    • We use a binary search tree that is balanced (AVL/Red-Black/etc), but not super-balanced like you described. So adding an item is O(log n)
    • One modification to the tree: for every node we also store the number of nodes in its subtree. This doesn't change the complexity. (For a leaf this count would be 1, for a node with two leaf children this would be 3, etc)

    We can now access the Kth smallest element in O(log n) using these counts:

    def get_kth_item(subtree, k):
      left_size = 0 if subtree.left is None else subtree.left.size
      if k < left_size:
        return get_kth_item(subtree.left, k)
      elif k == left_size:
        return subtree.value
      else: # k > left_size
        return get_kth_item(subtree.right, k-1-left_size)
    

    A median is a special case of Kth smallest element (given that you know the size of the set).

    So all in all this is another O(log n) solution.

提交回复
热议问题