力扣_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
相关推荐
eachin_z2 分钟前
力扣刷题(第四十九天)
算法·leetcode·职场和发展
飞川撸码3 小时前
【LeetCode 热题100】网格路径类 DP 系列题:不同路径 & 最小路径和(力扣62 / 64 )(Go语言版)
算法·leetcode·golang·动态规划
Zfox_5 小时前
Redis:Hash数据类型
服务器·数据库·redis·缓存·微服务·哈希算法
_Itachi__11 小时前
LeetCode 热题 100 74. 搜索二维矩阵
算法·leetcode·矩阵
chao_78912 小时前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表
编程绿豆侠14 小时前
力扣HOT100之多维动态规划:1143. 最长公共子序列
算法·leetcode·动态规划
dying_man1 天前
LeetCode--24.两两交换链表中的结点
算法·leetcode
yours_Gabriel1 天前
【力扣】2434.使用机器人打印字典序最小的字符串
算法·leetcode·贪心算法
GGBondlctrl1 天前
【leetcode】递归,回溯思想 + 巧妙解法-解决“N皇后”,以及“解数独”题目
算法·leetcode·n皇后·有效的数独·解数独·映射思想·数学思想