Faster algorithm to find unique element between two arrays?

后端 未结 9 1837
野性不改
野性不改 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:41

    This is a little bit faster:

    public static int getUniqueElement(int[] a, int[] b) {
        int ret = 0;
        int i;
        for (i = 0; i < a.length; i++) {
            ret += (a[i] - b[i]);
        }
        return Math.abs(ret - b[i]);
    }
    

    It's O(m), but the order doesn't tell the whole story. The loop part of the "official" solution has about 3 * m + 3 * n operations, and the slightly faster solution has 4 * m.

    (Counting the loop "i++" and "i < a.length" as one operation each).

    -Al.

提交回复
热议问题