Optimal inversion counting on int arrays

前端 未结 3 770
难免孤独
难免孤独 2021-02-08 23:30

Today I was looking the latest exam of the local informatics olympiad and I found a interesting problem. Briefly, it asks to, given an integer array, count how many inversions i

3条回答
  •  遇见更好的自我
    2021-02-09 00:13

    If we assume the number of bits used to represent the integer is constant (say 32 or 64 bits), this can be solved in O(N) time.

    Here is an example python implementation.

    http://ideone.com/g57O87

    
    def inv_count(a, m=(1<<32)):
      if not m or not a:
          return 0
      count = 0
      ones = []
      zeros = []
      for n in a:
        if n & m:
          ones.append(n & ~m)
        else:
          count += len(ones)
          zeros.append(n & ~m)
      m /= 2
      return count + inv_count(ones, m) + inv_count(zeros, m)

    print inv_count([1, 2, 3, 4, 5]) print inv_count([5, 4, 3, 2, 1])

    We are able to achieve less than O(N x Log(N)) time complexity, as we are using idea behind a non-comparative sorting algorithm, radix sort, to get the count.

提交回复
热议问题