一、Problem
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].
Input: dominoes = [[1,2],[2,1],[3,4],[5,6]]
Output: 1
Constraints:
1 <= dominoes.length <= 40000
1 <= dominoes[i][j] <= 9
二、Solution
方法一:排序
暴力会超时,而这里求的实际上是两个数组的元素互换位置之后看是否相等,比如
a:[1,2],
b:[2,1], a、b是相等的,因为 a[0] = b[1],a[1] = b[0]
c:[1,2] ,a、c也肯定相等啦
如何让他们看起来一样呢?没错互换一下位置,如果他们转为数字后仍然相等,那么他们就是等价的
class Solution {
public int numEquivDominoPairs(int[][] ds) {
int cnt = 0, mp[] = new int[100];
for (int[] d : ds) {
Arrays.sort(d);
cnt += mp[d[0]*10 + d[1]]++;
}
return cnt;
}
}
复杂度分析
- 时间复杂度:,
- 空间复杂度:,