given an array, for each element, find out the total number of elements lesser than it, which appear to the right of it

后端 未结 10 1800
傲寒
傲寒 2021-02-04 11:43

I had previously posted a question, Given an array, find out the next smaller element for each element now, i was trying to know , if there is any way to find out \"given an ar

10条回答
  •  日久生厌
    2021-02-04 12:06

    It can be solved in O(n log n).

    If in a BST you store the number of elements of the subtree rooted at that node when you search the node (reaching that from the root) you can count number of elements larger/smaller than that in the path:

    int count_larger(node *T, int key, int current_larger){
        if (*T == nil)
            return -1;
        if (T->key == key)
            return current_larger + (T->right_child->size);
        if (T->key > key)
            return count_larger(T->left_child, key, current_larger + (T->right_child->size) + 1);
        return count_larger(T->right_child, key, current_larger)
    }
    

    ** for example if this is our tree and we're searching for key 3, count_larger will be called for:

    -> (node 2, 3, 0)
    --> (node 4, 3, 0)
    ---> (node 3, 3, 2)

    and the final answer would be 2 as expected.

提交回复
热议问题