825. 适龄的朋友

exiaohu 于 2021-12-27 发布

题目链接:825. 适龄的朋友

注意,年龄的范围只有 ${1, 2, 3, \dots, 120}$ 之间的值,这个范围并不大。因此首先计算出合法的每对会发送年龄请求的年龄,再分情况统计:

  1. 年龄相等的人可能发送好友请求,假设人数为 $age_i$,此时发送的好友请求数为 $A^{2}_{age_i}$;

  2. 年龄不相等的人之间可能发送好友请求,假设人数为 $age_i$ 和 $age_j$,此时发送的好友请求数为 $age_i \times age_j$。

from itertools import permutations, product
from collections import Counter
from typing import List


class Solution:
    def __init__(self):
        ages = range(1, 121)
        self.pairs = {(x, y) for x, y in product(ages, ages) if not (y <= 0.5 * x + 7 or y > x or (y > 100 > x))}

    def numFriendRequests(self, _ages: List[int]) -> int:
        if len(_ages) < 2:
            return 0

        ages, ans = Counter(_ages), 0

        for age in ages:
            if (age, age) in self.pairs:
                ans += ages[age] * (ages[age] - 1)

        for x, y in permutations(ages, 2):
            if (x, y) in self.pairs:
                ans += ages[x] * ages[y]

        return ans