Given a list of
Return the number of pairs
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
Approach
Java
import java.util.Arrays;import java.util.HashMap;public class NumberEquivalentPair {public static void main(String[] args) {int[][] dominoes = { { 1, 2 }, { 2, 1 }, { 3, 4 }, { 5, 6 } };System.out.println(numEquivDominoPairs(dominoes));}static int numEquivDominoPairs(int[][] dominoes) {HashMap<Pair, Integer> mp = new HashMap<Pair, Integer>();int cnt = 0;for (int i = 0; i < dominoes.length; i++) {int[] x = dominoes[i];Arrays.sort(x);Pair p = new Pair(x[0], x[1]);if (mp.containsKey(p))cnt += mp.get(p);mp.put(p, mp.getOrDefault(p, 0) + 1);}return cnt;}static class Pair {private int first;private int second;public Pair(int first, int second) {super();this.first = first;this.second = second;}public int getFirst() {return first;}public void setFirst(int first) {this.first = first;}public int getSecond() {return second;}public void setSecond(int second) {this.second = second;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + first;result = prime * result + second;return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Pair other = (Pair) obj;if (first != other.first)return false;if (second != other.second)return false;return true;}}}
C++
#include <bits/stdc++.h>using namespace std;int numEquivDominoPairs(vector<vector<int>> &dominoes){map<vector<int>, int> mp;int cnt = 0;for (int i = 0; i < dominoes.size(); i++){vector<int> x = dominoes[i];sort(x.begin(), x.end());if (mp.find(x) != mp.end())cnt += mp[x];mp[x]++;}return cnt;}int main(){vector<vector<int>> dominoes = {{1, 2}, {2, 1}, {3, 4}, {5, 6}};cout << numEquivDominoPairs(dominoes);return 0;}
No comments:
Post a Comment