1128. Number of Equivalent Domino Pairs

# 1128. Number of Equivalent Domino Pairs#

## 题目 #

Given a list of `dominoes``dominoes[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`

## 题目大意 #

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

## 解题思路 #

• 给出一组多米诺骨牌，求出这组牌中相同牌的个数。牌相同的定义是：牌的 2 个数字相同(正序或者逆序相同都算相同)
• 简单题。由于牌是 2 个数，所以将牌的 2 个数 hash 成一个 2 位数，比较大小即可，正序和逆序都 hash 成 2 位数，然后在桶中比较是否已经存在，如果不存在，跳过，如果存在，计数。

## 代码 #

``````
package leetcode

func numEquivDominoPairs(dominoes [][]int) int {
if dominoes == nil || len(dominoes) == 0 {
return 0
}
result, buckets := 0, [100]int{}
for _, dominoe := range dominoes {
key, rotatedKey := dominoe[0]*10+dominoe[1], dominoe[1]*10+dominoe[0]
if dominoe[0] != dominoe[1] {
if buckets[rotatedKey] > 0 {
result += buckets[rotatedKey]
}
}
if buckets[key] > 0 {
result += buckets[key]
buckets[key]++
} else {
buckets[key]++
}
}
return result
}

``````

Apr 8, 2023