力扣_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
相关推荐
逐花归海.10 小时前
『 C++ 入门到放弃 』- 哈希表
数据结构·c++·程序人生·哈希算法·散列表
এ᭄画画的北北11 小时前
力扣-51.N皇后
算法·leetcode
1白天的黑夜111 小时前
前缀和-974.和可被k整除的子数组-力扣(LeetCode)
c++·leetcode·前缀和
12 小时前
LeetCode Hot 100 搜索二维矩阵
算法·leetcode·矩阵
小新学习屋12 小时前
《剑指offer》-算法篇-位运算
python·算法·leetcode·职场和发展·数据结构与算法
鼠鼠一定要拿到心仪的offer12 小时前
Day23-二叉树的层序遍历(广度优先搜素)
数据结构·算法·leetcode
YuTaoShao12 小时前
【LeetCode 热题 100】34. 在排序数组中查找元素的第一个和最后一个位置——二分查找
java·数据结构·算法·leetcode
Swift社区13 小时前
从字符串中“薅出”最长子串:LeetCode 340 Swift 解法全解析
算法·leetcode·swift
吃着火锅x唱着歌15 小时前
LeetCode 1616.分割两个字符串得到回文串
算法·leetcode·职场和发展
Gerry_Liang18 小时前
LeetCode热题100——155. 最小栈
算法·leetcode·职场和发展