这是我参与更文挑战的第7天,活动详情查看: 更文挑战
描述
Given a list of 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
Note:
1 <= dominoes.length <= 40000
1 <= dominoes[i][j] <= 9
解析
根据题意,只要 i<j ,dominoes[i] 和 dominoes[j] 中的内容一样(顺序无所谓),即可算作一对。逻辑简单,先将 dominoes 按照元素的和从小到大进行排序,然后判断当前元素 dominoes[i] 与其和相同的后面的 dominoes[j] 元素是否满足要求,如果是则计数器加 1 ,不是则与其他和相同的 dominoes[x] 进行比较。当和不相同的时候,则从 dominoes[i+1] 开始重复执行上面的过程。 最后得到的计数器数值即为结果。
解答
class Solution(object):
def numEquivDominoPairs(self, dominoes):
"""
:type dominoes: List[List[int]]
:rtype: int
"""
dominoes = sorted(dominoes, key=lambda x:sum(x))
N = len(dominoes)
count = 0
i=0
while i<N-1:
s = sum(dominoes[i])
for j in range(i+1,N):
if s == sum(dominoes[j]):
if (dominoes[i][0] == dominoes[j][0] and dominoes[i][1] == dominoes[j][1]) or (dominoes[i][0] == dominoes[j][1] and dominoes[i][1] == dominoes[j][0]):
count += 1
else:
continue
else:
break
i+=1
return count
运行结果
Time Limit Exceeded
解析
其实对 dominoes 中的每个元素进行排序,保证内容一样的元素,其顺序也一样,然后对 dominoes 中的元素进行计数保存到字典 d 中,然后遍历 d 中的 v ,将 v*(v-1)//2 加到计数器,遍历结束得到的计数器即可结果。
解答
class Solution(object):
def numEquivDominoPairs(self, dominoes):
"""
:type dominoes: List[List[int]]
:rtype: int
"""
for i in range(len(dominoes)):
dominoes[i].sort()
d = {}
for i in dominoes:
i = tuple(i)
if i in d:
d[i]+=1
else:
d[i] = 1
c = 0
for k,v in d.items():
c += v*(v-1)//2
return c
运行结果
Runtime: 196 ms, faster than 77.78% of Python online submissions for Number of Equivalent Domino Pairs.
Memory Usage: 25.3 MB, less than 86.42% of Python online submissions for Number of Equivalent Domino Pairs.
原题链接:leetcode.com/problems/nu…
您的支持是我最大的动力