0
点赞
收藏
分享

微信扫一扫

模拟卷Leetcode【普通】825. 适龄的朋友

i奇异 2022-04-13 阅读 18

825. 适龄的朋友

在社交媒体网站上有 n 个用户。给你一个整数数组 ages ,其中 ages[i] 是第 i 个用户的年龄。

如果下述任意一个条件为真,那么用户 x 将不会向用户 y(x != y)发送好友请求:

age[y] <= 0.5 * age[x] + 7
age[y] > age[x]
age[y] > 100 && age[x] < 100
否则,x 将会向 y 发送一条好友请求。

注意,如果 x 向 y 发送一条好友请求,y 不必也向 x 发送一条好友请求。另外,用户不会向自己发送好友请求。

返回在该社交媒体网站上产生的好友请求总数。

示例 1:

输入:ages = [16,16]
输出:2
解释:2 人互发好友请求。
示例 2:

输入:ages = [16,17,18]
输出:2
解释:产生的好友请求为 17 -> 16 ,18 -> 17 。
示例 3:

输入:ages = [20,30,100,110,120]
输出:3
解释:产生的好友请求为 110 -> 100 ,120 -> 110 ,120 -> 100 。

提示:

n == ages.length
1 <= n <= 2 * 104
1 <= ages[i] <= 120

代码:

from leetcode_python.utils import *


class Solution:
    def numFriendRequests(self, ages: List[int]) -> int:
        ages.sort()
        res,length = 0,len(ages)
        for i in range(length):
            x = ages[i]
            left = bisect.bisect_right(ages,0.5*x+7)
            right = bisect.bisect_right(ages,x)
            res += max(0,right-left-1)
            # print(i,left,i-left)
        return res


def test(data_test):
    s = Solution()
    data = data_test  # normal
    # data = [list2node(data_test[0])]  # list转node
    return s.numFriendRequests(*data)


def test_obj(data_test):
    result = [None]
    obj = Solution(*data_test[1][0])
    for fun, data in zip(data_test[0][1::], data_test[1][1::]):
        if data:
            res = obj.__getattribute__(fun)(*data)
        else:
            res = obj.__getattribute__(fun)()
        result.append(res)
    return result


if __name__ == '__main__':
    datas = [
        [[16,16]],
        [[16,17,18]],
        # [[20,30,100,110,120]],
    ]
    for data_test in datas:
        t0 = time.time()
        print('-' * 50)
        print('input:', data_test)
        print('output:', test(data_test))
        print(f'use time:{time.time() - t0}s')

备注:
GitHub:https://github.com/monijuan/leetcode_python

CSDN汇总:模拟卷Leetcode 题解汇总_卷子的博客-CSDN博客

可以加QQ群交流:1092754609

举报

相关推荐

0 条评论