LeetCode题解(1029):两地最优调度(Python)
发布日期:2021-06-29 19:55:15 浏览次数:3 分类:技术文章

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

题目:(简单)

解法 时间复杂度 空间复杂度 执行用时
Ans 1 (Python) O ( N l o g N ) O(NlogN) O(NlogN) O ( N ) O(N) O(N) 48ms (87.28%)
Ans 2 (Python) O ( N l o g N ) O(NlogN) O(NlogN) O ( N ) O(N) O(N) 44ms (97.01%)
Ans 3 (Python)

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

解法一(自定义排序):

def twoCitySchedCost(self, costs: List[List[int]]) -> int:    def differ(cost):        return cost[0] - cost[1]    costs.sort(key=differ)    center = len(costs) // 2    ans = 0    for i in range(center):        ans += costs[i][0]    for i in range(center, len(costs)):        ans += costs[i][1]    return ans

解法二(优雅化):

def twoCitySchedCost(self, costs: List[List[int]]) -> int:    costs.sort(key=lambda cost: cost[0] - cost[1])    center = len(costs) // 2    ans = 0    for i in range(center):        ans += costs[i][0] + costs[i + center][1]    return ans

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

上一篇:LeetCode题解(1030):距离顺序排序矩阵单元格(Python)
下一篇:LeetCode题解(1025):除数博弈游戏(Python)

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月08日 19时40分22秒

关于作者

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

推荐文章