力扣_day1

两数之和

hash表的时间复杂度为什么是O(1)?

hash表是基于数组+链表的实现的。数组在内存中是一块连续的空间,只要知道查找数据的下标就可快速定位到数据的内存地址,即数组查找数据的时间复杂度为O(1)。

能用一次循环解决问题就用一次循环。

python 复制代码
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        has = {}
        for i in range(len(nums)):
            key = target - nums[i]
            if key in has:
                return i, has[key]
            has[nums[i]] = i
相关推荐
小欣加油34 分钟前
leetcode 面试题01.02判定是否互为字符重排
数据结构·c++·算法·leetcode·职场和发展
3Cloudream38 分钟前
LeetCode 003. 无重复字符的最长子串 - 滑动窗口与哈希表详解
算法·leetcode·字符串·双指针·滑动窗口·哈希表·中等
林木辛5 小时前
LeetCode热题 42.接雨水
算法·leetcode
黑菜钟7 小时前
代码随想录第七天|● 454.四数相加II ● 383. 赎金信 ● 15. 三数之和 18.四数之和
c++·算法·leetcode
pzx_0019 小时前
【LeetCode】14. 最长公共前缀
算法·leetcode·职场和发展
songx_999 小时前
leetcode10(跳跃游戏 II)
数据结构·算法·leetcode
1白天的黑夜113 小时前
哈希表-49.字母异位词分组-力扣(LeetCode)
c++·leetcode·哈希表
愚润求学14 小时前
【贪心算法】day7
c++·算法·leetcode·贪心算法
共享家95271 天前
优先搜索(DFS)实战
算法·leetcode·深度优先
flashlight_hi1 天前
LeetCode 分类刷题:2563. 统计公平数对的数目
python·算法·leetcode