Finding the index of a given permutation

前端 未结 7 562
闹比i
闹比i 2020-12-10 15:38

I\'m reading the numbers 0, 1, ..., (N - 1) one by one in some order. My goal is to find the lexicography index of this given permutation, using only O(1)

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 16:02

    Here is a way to do it if you want to assume that arithmetic operations are constant time:

    def permutationIndex(numbers):
      n=len(numbers)
      result=0
      j=0
      while j

    I've purposefully written out certain calculations that could be done more simply using some Python built-in operations, but I wanted to make it more obvious that no extra non-constant amount of space was being used.

    As maxim1000 noted, the number of bits required to represent the result will grow quickly as n increases, so eventually big integers will be required, which no longer have constant-time arithmetic, but I think this code addresses the spirit of your question.

提交回复
热议问题