LeetCode题解(1030):距离顺序排序矩阵单元格(Python)
发布日期:2021-06-29 19:55:15
浏览次数:3
分类:技术文章
本文共 1008 字,大约阅读时间需要 3 分钟。
题目:(简单)
解法 | 时间复杂度 | 空间复杂度 | 执行用时 |
---|---|---|---|
Ans 1 (Python) | O ( R × C l o g ( R × C ) ) O(R×Clog(R×C)) O(R×Clog(R×C)) | O ( R × C ) O(R×C) O(R×C) | 212ms (32.52%) |
Ans 2 (Python) | O ( R × C l o g ( R × C ) ) O(R×Clog(R×C)) O(R×Clog(R×C)) | O ( R × C ) O(R×C) O(R×C) | 172ms (91.44%) |
Ans 3 (Python) |
LeetCode的Python执行用时随缘,只要时间复杂度没有明显差异,执行用时一般都在同一个量级,仅作参考意义。
解法一(自定义排序):
def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]: ans = [] for i in range(R): for j in range(C): ans.append([i, j]) ans.sort(key=lambda p: abs(p[0] - r0) + abs(p[1] - c0)) return ans
解法二:
def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]: ans = { } for i in range(R): for j in range(C): distance = abs(i - r0) + abs(j - c0) if distance not in ans: ans[distance] = [[i, j]] else: ans[distance].append([i, j]) res = [] for key in sorted(ans.keys()): res.extend(ans[key]) return res
转载地址:https://dataartist.blog.csdn.net/article/details/107101411 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月16日 23时50分10秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
为什么要有同源限制
2019-04-30
javascript 定义对象的方式
2019-04-30
常见兼容性问题
2019-04-30
promise 浅析
2019-04-30
jQuery源码值得借鉴的地方
2019-04-30
vue、react、angular小小比较
2019-04-30
Node的应用场景
2019-04-30
js数据类型
2019-04-30
js有哪些内置对象
2019-04-30
eval是做什么的
2019-04-30
null,undefined 的区别
2019-04-30
javascript 代码中的“use strict“
2019-04-30
JSON 的了解
2019-04-30
defer和async
2019-04-30
严格模式的限制
2019-04-30
attribute和property的区别是什么
2019-04-30
面向对象编程思想
2019-04-30
reactNative 打包报错 mergeReleaseResources
2019-04-30
对web标准、可用性、可访问性的理解
2019-04-30