一、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;
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,