LeetCode题解(0001):两数之和(Python)
发布日期:2021-06-29 19:51:33
浏览次数:2
分类:技术文章
本文共 1199 字,大约阅读时间需要 3 分钟。
LeetCode题解:0001(哈希表的应用)
解法 | 时间复杂度 | 空间复杂度 | 执行用时 | 内存消耗 |
---|---|---|---|---|
Ans 1 (Python) | O ( N 2 ) O(N^2) O(N2) | O ( 1 ) O(1) O(1) | 5564ms (>21.06%) | 14.5MB (>13.41%) |
Ans 2 (Python) | O ( N 2 ) O(N^2) O(N2) | O ( 1 ) O(1) O(1) | 872ms (>41.68%) | 14.5MB (>13.41%) |
Ans 3 (Python) | O ( N ) O(N) O(N) | O ( N ) O(N) O(N) | 56ms (>77.63%) | 15.1MB (>5.48%) |
解法一(直接两次遍历):
def twoSum(self, nums: List[int], target: int) -> List[int]: for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return [i, j]
解法二(使用使用列表的__contain()__方法替换第二层遍历):
def twoSum(self, nums: List[int], target: int) -> List[int]: for i in range(len(nums)): another = target - nums[i] if another in nums[(i + 1):]: return [i, nums[(i + 1):].index(another) + i + 1]
其中列表的contain or in方法的时间复杂度为 O ( N ) O(N) O(N),index方法的时间复杂度为 O ( N ) O(N) O(N)()
解法三(使用哈希表存储已经遍历过的数,因为查找哈希表的时间复杂度为 O ( 1 ) O(1) O(1)):
def twoSum(self, nums: List[int], target: int) -> List[int]: hashmap = { } for index, num in enumerate(nums): another_num = target - num if another_num in hashmap: return [hashmap[another_num], index] hashmap[num] = index
转载地址:https://dataartist.blog.csdn.net/article/details/106741506 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月15日 21时50分36秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
gaussdb200 数据导入
2019-04-30
superset 报表
2019-04-30
sqoop 原理与部署
2019-04-30
sqoop 实操
2019-04-30
kerberos 环境 MapReduce 跨平台提交
2019-04-30
欧洲杯上那让人惊叹的vivo蓝
2019-04-30
百度昆仑芯片独立背后,或向汽车芯片发起进军
2019-04-30
月活达10亿后,未来快手的“无限”可能
2019-04-30
关于回调注销问题的总结
2019-04-30
Android学习开发路线图
2019-04-30
开发Android主攻四大方向
2019-04-30
Android开发方向
2019-04-30
RAW格式
2019-04-30
Android6.0以上文件读写权限
2019-04-30
Android数据文件存储路径
2019-04-30
LINUX下的SD卡分区
2019-04-30
GDB的使用
2019-04-30
USB摄像头到ARM下图像显示方案
2019-04-30
Android消息处理Handler与Message
2019-04-30