LeetCode Weekly Contest 146

1128. Number of Equivalent Domino Pairs

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==dand 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].

 

Example 1:

Input: dominoes = [[1,2],[2,1],[3,4],[5,6]]
Output: 1

 

Constraints:

  • 1 <= dominoes.length <= 40000
  • 1 <= dominoes[i][j] <= 9

Topic effect: to give you a digital array of key-value pairs, let you determine how many array elements are equal. Two keys for equal conditions: Key 1 and Key 2 = 1 = 1 = value 2 or the value of the key 2 and the key value 2 = 1.

Ideas: the keys and put preceded by "_" and a smaller number of key as key map is stored map, and then traverse the map like sum. (In fact, you can key in a smaller number by 100 or 1000 and then add a large number of the key, but when the race, my mind did not turn, used this method, but also the AC)

class Solution {
    public int numEquivDominoPairs(int[][] dominoes) {
        Map<String, Integer> map = new HashMap<>();
        int len = dominoes.length;
        for(int i=0; i<len; i++) {
            int a = dominoes[i][0];
            int b = dominoes[i][1];
            String te = a+b + "-";
            if( a > b ) te = te + b;
            else te = te + a;
            Integer cnt = map.get(te);
            if( cnt==null ) {
                map.put(te, 1);
            } else {
                map.put(te, cnt+1);
            }
        }
        int sum = 0;
        for(Map.Entry<String, Integer> entry : map.entrySet() ) {
            int v = entry.getValue();
            sum += (v*(v-1))/2;
        }
        return sum;
    }
}
View Code

 

Guess you like

Origin www.cnblogs.com/Asimple/p/11258542.html