【leetcode】1128. Number of Equivalent Domino Pairs

题目如下:

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

解题思路:题目本身不难,遍历dominoes,依次把(dominoes[i][0],dominoes[i][1])当做key值存入字典中,存入之前,先求出(dominoes[i][0],dominoes[i][1])出现的次数,出现了多少次就说明在0~i-1区间内与其等价的个数。如果dominoes[i][0]不等于dominoes[i][1],那么还需加上(dominoes[i][1],dominoes[i][0])在字典中出现的次数。

代码如下:

class Solution(object):
    def numEquivDominoPairs(self, dominoes):
        """
        :type dominoes: List[List[int]]
        :rtype: int
        """
        dic = {}
        res = 0
        for (i,j) in dominoes:
            if (i,j) in dic:
                res += dic[(i,j)]
            if i !=j and (j,i) in dic:
                res += dic[(j,i)]
            dic[(i,j)] = dic.setdefault((i,j),0) + 1
        return res
原文地址:https://www.cnblogs.com/seyjs/p/11231881.html