枚举右、维护左

Leetcode 1512. 好数对的数目

class Solution:
    def numIdenticalPairs(self, nums: List[int]) -> int:
        ans = 0
        cnt = collections.defaultdict(int)
        for j, x in enumerate(nums):
            if x in cnt:
                ans += cnt[x]
            cnt[x] += 1
        return ans

Leetcode 2001. 可互换矩形的组数

class Solution:
    """
    方法一:枚举右维护左
        时间复杂度O(n)
        空间复杂度O(n)
    """

    def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:
        ans = 0
        cnt = collections.defaultdict(int)
        for j, matrix in enumerate(rectangles):
            if matrix[0] / matrix[1] in cnt:
                ans += cnt[matrix[0] / matrix[1]]
            cnt[matrix[0] / matrix[1]] += 1
        return ans

Leetcode 1128. 等价多米诺骨牌对的数量

class Solution:
    def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
        ans = 0
        cnt = collections.defaultdict(int)
        for j, x in enumerate(dominoes):
            # 列表list是不可哈希的,所以用元组tuple
            if (x[0], x[1]) in cnt:
                ans += cnt[(x[0], x[1])]
            if x[0] != x[1] and (x[1], x[0]) in cnt:
                ans += cnt[(x[1], x[0])]
            cnt[(x[0], x[1])] += 1
        return ans

上述很多例题都可以用组合数学技巧优化(求...共有几对),不再赘述。

标签: none

添加新评论