【贪心】C043_LC_等价多米诺骨牌对的数量(消除差异)

一、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;
    }
}

复杂度分析

  • 时间复杂度:O(n×2log2)O(n × 2log2)
  • 空间复杂度:O(1)O(1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章