Faster algorithm to find unique element between two arrays?

后端 未结 9 1840
野性不改
野性不改 2020-12-22 20:20

EDIT: For anyone new to this question, I have posted an answer clarifying what was going on. The accepted answer is the one I feel best answers my question

9条回答
  •  独厮守ぢ
    2020-12-22 20:29

    Let's say that there are two unsorted integer arrays a and b, with element repetition allowed. They are identical (with respect to contained elements) except one of the arrays has an extra element ..

    You may note that I emphasised two point in your original question, and I'm adding an extra assumption of that the values are non-zero.

    In C#, you can do this:

    int[, , , , ,] a=new int[6, 5, 6, 3, 4, 2];
    int[, , , , , ,] b=new int[5, 7, 6, 6, 2, 3, 4];
    Console.WriteLine(b.Length/a.Length);
    

    See? Whatever the extra element is, you will always know it by simply dividing their length.

    With these statements, we are not storing the given series of integers as values to arrays, but as their dimensions.

    As whatever the shorter series of integers is given, the longer one should have only one extra integer. So no matter the order of the integers, without the extra one, the total size of these two multi-dimensional array are identical. The extra dimension times the size of the longer, and to divide by the size of the shorter, we know what is the extra integer.

    This solution would works only for this particular case as I quoted from your question. You might want to port it to Java.

    This is just a trick, as I thought the question itself is a trick. We definitely will not consider it as a solution for production.

提交回复
热议问题