LeetCode题解(1010):总持续时间可被60整除的歌曲(Python)
发布日期:2021-06-29 19:55:11 浏览次数:3 分类:技术文章

本文共 1176 字,大约阅读时间需要 3 分钟。

题目:(简单)

解法 时间复杂度 空间复杂度 执行用时
Ans 1 (Python) O ( N 2 ) O(N^2) O(N2) O ( 1 ) O(1) O(1) 超出时间限制
Ans 2 (Python) O ( N 2 ) O(N^2) O(N2) O ( N ) O(N) O(N) 超出时间限制
Ans 3 (Python) O ( N ) O(N) O(N) O ( 1 ) O(1) O(1) 264ms (92.32%)

LeetCode的Python执行用时随缘,只要时间复杂度没有明显差异,执行用时一般都在同一个量级,仅作参考意义。

解法一(暴力方法,直接枚举求余):

def numPairsDivisibleBy60(self, time: List[int]) -> int:    ans = 0    for pair in itertools.combinations(time, 2):        if (pair[0] + pair[1]) % 60 == 0:            ans += 1    return ans

解法二(更好的暴力,先求余再枚举):

def numPairsDivisibleBy60(self, time: List[int]) -> int:    time = [t % 60 for t in time]    ans = 0    for pair in itertools.combinations(time, 2):        remainder = pair[0] + pair[1]        if remainder == 0 or remainder == 60:            ans += 1    return ans

解法三:

def numPairsDivisibleBy60(self, time: List[int]) -> int:    count = collections.Counter([t % 60 for t in time])    ans = 0    if 0 in count:        n = count[0]        ans += n * (n - 1) / 2    if 30 in count:        n = count[30]        ans += n * (n - 1) / 2    for k, v in count.items():        if k < 30 and 60 - k in count:            n = count[60 - k]            ans += v * n    return int(ans)

转载地址:https://dataartist.blog.csdn.net/article/details/107098737 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode题解(1013):将数组分成和相等的三个部分(Python)
下一篇:LeetCode题解(1009):十进制整数的反码(Python)

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月27日 12时04分08秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章