[LeetCode] 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==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

这道题给了一个多米诺数组,每个多米诺有两个数字,现在让找有多少个相同的多米诺,由于多米诺可以旋转,所以这里两个数字的顺序并不重要。虽然说是一道简单的题目,但是暴力搜索法还是不可取的,太不高效了,最好的还是直接统计相同的牌的数量,再来计算相同的 pair 对儿个数。若多米诺不能翻转,直接进行统计就行了,现在能翻转,就要统一用个方法来标记翻转后相同的多米诺,这里可以始终将小的放在前面。又由于数字只有1到9,所以可以把较小的数字编码到十位上,较大的数字编码到个位上,这样组成的两位数就可以表示独特的多米诺了。统计完相同的多米诺个数之后就可以计算相同的 pair 对儿了,若有n个相同的多米诺,则共有 n(n-1)/2 个相同的 pair 对儿,这样就可以算出总共相同的 pair 对儿个数了,参见代码如下:


解法一:

class Solution {
public:
    int numEquivDominoPairs(vector<vector<int>>& dominoes) {
        int res = 0;
        unordered_map<int, int> cntMap;
        for (auto &d : dominoes) {
            ++cntMap[min(d[0], d[1]) * 10 + max(d[0], d[1])];
        }
        for (auto &a : cntMap) {
            res += a.second * (a.second - 1) / 2;
        }
        return res;
    }
};

其实我们不用在最后单独计算 pair 对儿的个数,而是可以边统计边累加,当计算出某个多米诺的编码值之后,可以将其在 HashMap 中的映射值直接加到结果 res 中(若从未出现过,则加上的是0,不影响结果),然后再将其映射值加1,这里表示当前新的这个多米诺可以跟之前所有的多米诺都组成一个新的 pair 对儿,参见代码如下:


解法二:

class Solution {
public:
    int numEquivDominoPairs(vector<vector<int>>& dominoes) {
        int res = 0;
        unordered_map<int, int> cntMap;
        for (auto &d : dominoes) {
            res += cntMap[min(d[0], d[1]) * 10 + max(d[0], d[1])]++;
        }
        return res;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1128


参考资料:

https://leetcode.com/problems/number-of-equivalent-domino-pairs/

https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/340022/JavaC%2B%2BPython-Easy-and-Concise

https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/339969/JavaPython-3-O(n)-code-with-brief-explanation-and-analysis.


LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2021-05-24 02:24  Grandyang  阅读(372)  评论(0编辑  收藏  举报
Fork me on GitHub