Skip to content

Latest commit

 

History

History
87 lines (76 loc) · 2.44 KB

File metadata and controls

87 lines (76 loc) · 2.44 KB

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

Related Topics:
Array

Solution 1.

// OJ: https://leetcode.com/problems/number-of-equivalent-domino-pairs/
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(N)
class Solution {
public:
    int numEquivDominoPairs(vector<vector<int>>& A) {
        map<vector<int>, int> m;
        int ans = 0;
        for (auto &v : A) {
            sort(begin(v), end(v));
            ans += m[v];
            m[v]++;
        }
        return ans;
    }
};

Solution 2.

// OJ: https://leetcode.com/problems/number-of-equivalent-domino-pairs/
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(1)
class Solution {
public:
    int numEquivDominoPairs(vector<vector<int>>& A) {
        for (auto &v : A) sort(begin(v), end(v));
        sort(begin(A), end(A));
        int ans = 0;
        for (int i = 0, N = A.size(); i < N;) {
            int start = i;
            while (i < N && A[i] == A[start]) ++i;
            int len = i - start;
            ans += (len - 1) * len / 2;
        }
        return ans;
    }
};

Solution 3.

// OJ: https://leetcode.com/problems/number-of-equivalent-domino-pairs/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    int numEquivDominoPairs(vector<vector<int>>& A) {
        int cnt[10][10] = {}, ans = 0;
        for (auto &v : A) {
            if (v[0] > v[1]) swap(v[0], v[1]);
            ans += cnt[v[0]][v[1]]++;
        }
        return ans;
    }
};