Title from LeetCode, link: Number The-equivalent-of-the Domino-pairs . Specifically described as: to give you a list of dominoes domino composed by a number. If one can get a domino dominoes another by rotating 0 degrees or 180 degrees, we believe these two cards are equivalent. Formally, dominoes [i] = [a , b] and the dominoes [j] = [c, d] is equivalent to premise a == c and b == d, or a == d and b == c . At 0 <= i <j premise <dominoes.length to find out the number of dominoes [i] and the dominoes [j] domino equivalent to (i, j) is satisfied. prompt:
- 1 <= dominoes.length <= 40000
- 1 <= dominoes[i][j] <= 9
Example:
输入:dominoes = [[1,2],[2,1],[3,4],[5,6]]
输出:1
A very easy to think of the idea is to do with each domino key, the number of occurrences do value, the final value is assumed to be n, then This is the number of domino pair. Of course, the array do not key, at the beginning do not know these arrays are a length of 2 so the first turn of the string, and later found the array length is 2, so much easier, that is directly converted to a double-digit may, however, since the reverse order, when it is necessary to generate decimal agreed in large numbers after the front, such as [1,2] -> 12, [2,1] -> 12. Taking into account the size of this figure will not exceed 100, so you can not dictionary / Map, directly in an array, a 100-length value (the actual figure may be only 45 species, can further reduce space requirements).
Computing dominoes can calculate all of the time the number of And the sum, but may be accumulated during traversal directly, which can be see, as long as the current array traversal has occurred, the number of times before it will be coupled with statistics, and then re-occurrences +1. The total time complexity is , the spatial complexity is .
JAVA version of the code is as follows:
class Solution {
public int numEquivDominoPairs(int[][] dominoes) {
int count = 0, key;
int[] record = new int[100];
for (int[] pair : dominoes) {
if (pair[0] < pair[1]) {
key = pair[0] * 10 + pair[1];
}
else {
key = pair[1] * 10 + pair[0];
}
count += record[key]++;
}
return count;
}
}
Submit results were as follows:
Python version of the code is as follows:
class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
recordLst = [0 for i in range(100)] #数字最大为99
count = 0
for x, y in dominoes:
key = min(x, y) * 10 + max(x, y) #[1,2]->12, [2,1]->12
count += recordLst[key] #(n+1)n/2-n(n-1)/2=n
recordLst[key] += 1
return count
Submit results were as follows: