How to tell if an array is a permutation in O(n)?

后端 未结 16 1648
粉色の甜心
粉色の甜心 2020-12-07 10:17

Input: A read-only array of N elements containing integer values from 1 to N (some integer values can appear more than once!). And a memory zone of a fixed<

16条回答
  •  一向
    一向 (楼主)
    2020-12-07 10:32

    I don't know how to do it in O(N), or even if it can be done in O(N). I know that it can be done in O(N log N) if you (use an appropriate) sort and compare.

    That being said, there are many O(N) techniques that can be done to show that one is NOT a permutation of the other.

    1. Check the length. If unequal, obviously not a permutation.
    2. Create an XOR fingerprint. If the value of all the elements XOR'ed together does not match, then it can not be a permutation. A match would however be inconclusive.
    3. Find the sum of all elements. Although the result may overflow, that should not be a worry when matching this 'fingerprint'. If however, you did a checksum that involved multiplying then overflow would be an issue.

    Hope this helps.

提交回复
热议问题