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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode题解(1033):连续移动石子直到连续(Python)
下一篇:LeetCode题解(1029):两地最优调度(Python)

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月16日 23时50分10秒