Number of Equivalent Domino Pairs

Wasted years wasted years. Today, we pay a question.

The problem is the difficulty in leetcode in easy, I really did not finish, I really do not want to admit ah.

Topics are as follows:

Given a list of dominoesdominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a==c and b==d), or (a==d and b==c) - that is, one domino can be rotated to be equal to another domino.

Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j]

solution:

The beginning, I only thought of violence double for loop, with a private method which is used to compare whether it is equal. The result is that the test time complexity is too high, it has accept.

Read someone else's solution, original idea is that, as following code.

public int numEquivDominoPairs(int[][] dominoes) {
        int[] res = {0};
        Map<Integer, Integer> map =  new HashMap<>();
        int key = 0;
        for (int[] d : dominoes) {
            key = Math.min(d[0], d[1]) * 10 + Math.max(d[0], d[1]);
            map.put(key, map.getOrDefault(key, 0) + 1);
        }
        map.forEach((k, v) -> {
            res[0] += v * (v - 1) / 2;
        });
        return res[0];
    }

The idea is the element array is converted into a decimal number or a character string. The resulting number or string on the map inside. Permutations and combinations then a calculation result. res = C (2 / v)

The following solution is then directly counted accumulation results:

    public int numEquivDominoPairs(int[][] dominoes) {
        int res = 0;
        int key = 0;
        Map<Integer, Integer> map = new HashMap<>();
        for (int[] d : dominoes) {
            key = Math.min(d[0], d[1]) * 10 + Math.max(d[0], d[1]);
            res += map.getOrDefault(key, 0);
            map.put(key, map.getOrDefault(key, 0) + 1);
        }
        return res;
    }

 

Guess you like

Origin www.cnblogs.com/setnull/p/11237127.html