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

上一篇:LeetCode题解(0002):两链表逐项相加(Python)
下一篇:绝对干货的Twitter搜索技巧

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月15日 21时50分36秒