LeetCode题解(1042):不邻接种花/地图染色(Python)
发布日期:2021-06-29 19:55:19
浏览次数:3
分类:技术文章
本文共 1519 字,大约阅读时间需要 5 分钟。
题目:(简单)
解法 | 时间复杂度 | 空间复杂度 | 执行用时 |
---|---|---|---|
Ans 1 (Python) | O ( P + N ) O(P+N) O(P+N) | O ( P ) O(P) O(P) | 532ms (64.19%) |
Ans 2 (Python) | O ( P + N ) O(P+N) O(P+N) | O ( P ) O(P) O(P) | 476ms (98.90%) |
Ans 3 (Python) |
LeetCode的Python执行用时随缘,只要时间复杂度没有明显差异,执行用时一般都在同一个量级,仅作参考意义。
解法一(情景模拟+哈希表):
def gardenNoAdj(self, N: int, paths: List[List[int]]) -> List[int]: hashmap = { } for path in paths: if path[0] not in hashmap: hashmap[path[0]] = [path[1]] else: hashmap[path[0]].append(path[1]) if path[1] not in hashmap: hashmap[path[1]] = [path[0]] else: hashmap[path[1]].append(path[0]) color = [0 for _ in range(N + 1)] for i in range(1, N + 1): if i not in hashmap: color[i] = 1 else: apt = [1, 2, 3, 4] for near in hashmap[i]: if color[near] != 0 and color[near] in apt: apt.remove(color[near]) color[i] = apt[0] return color[1:]
解法二(将哈希表改为数组):
def gardenNoAdj(self, N: int, paths: List[List[int]]) -> List[int]: hashmap = [[] for _ in range(N + 1)] for path in paths: if path[0] > path[1]: hashmap[path[0]].append(path[1]) else: hashmap[path[1]].append(path[0]) color = [0 for _ in range(N + 1)] for i in range(1, N + 1): apt = [1, 2, 3, 4] for near in hashmap[i]: if color[near] != 0 and color[near] in apt: apt.remove(color[near]) color[i] = apt[0] return color[1:]
转载地址:https://dataartist.blog.csdn.net/article/details/107102642 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月30日 04时20分02秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
局部敏感哈希Locality Sensitive Hashing归总
2019-04-30
图像检索中为什么仍用BOW和LSH
2019-04-30
图˙谱˙马尔可夫过程˙聚类结构----by林达华
2019-04-30
深度学习读书笔记之AE(自动编码AutoEncoder)
2019-04-30
深度学习读书笔记之RBM
2019-04-30
深度学习word2vec笔记之基础篇
2019-04-30
用pair做优先队列priority_queue元素的例子
2019-04-30
堆优化的Dijkstra算法(邻接表+优先队列+pair)
2019-04-30
Nginx服务问题总结
2019-04-30
基于Vue的微信公众号开发及选型研究
2019-04-30
Vue项目中使用gif.js方法及注意事项
2019-04-30
软件设计的不同模型:瀑布式、快速原型法以及迭代式
2019-04-30
CuPlayer
2019-04-30
不要太在意
2019-04-30
给母亲的信
2019-04-30
jquery手风琴
2019-04-30
sql server 取文件名函数 转载
2019-04-30
jquery获取ul中的第一个li
2019-04-30