zoukankan      html  css  js  c++  java
  • 【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
  • 相关阅读:
    POJ3061(尺取法)
    POJ2739(尺取法)
    HDOJ4763(KMP原理理解)
    HDOJ5521(巧妙构建完全图)
    UVALive7261(2015ACM/ICPC北京赛区现场赛A)
    POJ1745动态规划
    POJ1273(最大流入门)
    HDOJ5883(欧拉路)
    HDOJ5437(优先队列)
    HDOJ5875(线段树)
  • 原文地址:https://www.cnblogs.com/seyjs/p/11231881.html
Copyright © 2011-2022 走看看