Find the number of unordered pair in an array

前端 未结 5 1381
囚心锁ツ
囚心锁ツ 2021-01-05 10:18

I ran into an interesting algorithm problem:

Given an array of integer, find the number of un-ordered pairs in that array, say given {1, 3, 2}, the answer is 1 becau

5条回答
  •  天命终不由人
    2021-01-05 10:46

    It is possible to solve this problem in O(n log n) time using a balanced binary search tree. Here is a pseudo-code of this algorithm:

    tree = an empty balanced binary search tree
    answer = 0
    for each element in the array:
         answer += number of the elements in the tree greater then this element
         add this element to the tree
    

提交回复
热议问题