Checking whether two numbers are permutation of each other?

前端 未结 7 2146
借酒劲吻你
借酒劲吻你 2021-02-15 22:44

Given two numbers a, b such that 1 <= a , b <= 10000000000 (10^10). My problem is to check whether the digits in them are permutation of each other or not. What is the fas

7条回答
  •  没有蜡笔的小新
    2021-02-15 23:26

    Create an array:

    int digitOccurances[2][10];
    

    In digitOccruances[X][N] store the number of times that the digit N appears in the number X. So if you were comparing 8675309 to 9568733, the array would end up looking like:

    { { 1, 0, 0, 1, 0, 1, 1, 1, 1, 1 } , { 0, 0, 0, 2, 0, 1, 1, 1, 1, 1 } }
    

    If the two arrays are equal, then the numbers are permutations.

    This is an O(n) algorithm, so asymptotically speaking this is the most efficient it's going to get (you can't solve this problem without examining all of the digits at least once.

    You can immediately return false if the numbers have different lengths, so assume that both of are of length n. It will take 2n operations to fill the array, and then exactly 10 comparisons to read the array. 2n + 10 is O(n).

提交回复
热议问题