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

后端 未结 10 1803
傲寒
傲寒 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:01

    Instead of BST, you can use stl map.

    Start inserting from right. After inserting an element, find its iterator:

    auto i = m.find(element);
    

    Then subtract it from m.end(). That gives you the number of elements in map which are greater than current element.

    map m;
    for (int i = array.size() - 1; i >= 0; --i) {
      m[array[i]] = true;
      auto iter = m.find(array[i])
      greaterThan[i] = m.end() - iter;
    }
    

    Hope it helped.

提交回复
热议问题