1128. Number of Equivalent Domino Pairs - Easy

Given a list of dominoesdominoes[i] = [a, b] is equivalentto 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].

 

Example 1:

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

 

Constraints:

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

 

hash table (naive): 把一个domino pair存入set,再作为key存入map,遍历dominoes,计数每个set出现多少次,最后再计算组合数求pair num

time: O(n), space: O(n)

class Solution {
    public int numEquivDominoPairs(int[][] dominoes) {
        Map<Set<Integer>, Integer> map = new HashMap<>();
        for(int[] domino : dominoes) {
            Set<Integer> set = new HashSet<>();
            set.add(domino[0]);
            set.add(domino[1]);
            
            map.put(set, map.getOrDefault(set, 0) + 1);
        }
        
        int res = 0;
        for(Map.Entry<Set<Integer>, Integer> entry: map.entrySet()) {
            int n = entry.getValue();
            if(n >= 2) {
                res += n * (n - 1) / 2;
            }
        }
        return res;
    }
}

 

optimized: 把一个domino pair处理成一个两位的数字,再作为key存入map

time: O(n), space: O(n)

class Solution {
    public int numEquivDominoPairs(int[][] dominoes) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int[] domino : dominoes) {
            int max = Math.max(domino[0], domino[1]);
            int min = Math.min(domino[0], domino[1]);
            int n = min * 10 + max;
            map.put(n, map.getOrDefault(n, 0) + 1);
        }
        
        int res = 0;
        for(Map.Entry<Integer, Integer> entry: map.entrySet()) {
            int n = entry.getValue();
            if(n >= 2) {
                res += n * (n - 1) / 2;
            }
        }
        return res;
    }
}

 

转载于:https://www.cnblogs.com/fatttcat/p/11334969.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值