力扣热100 哈希

哈希

1. 两数之和

题目 :给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。你可以按任意顺序返回答案。

示例 1:

输入:nums = [2,7,11,15], target = 9

输出:[0,1]

解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

python 复制代码
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
            table=collections.defaultdict(int)
            for index,num in enumerate(nums):
                if target-num in table:
                    return [index,table[target-num]]
                table[num]=index

49.字母异位词分组

题目 :给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

字母异位词 是由重新排列源单词的所有字母得到的一个新单词。

python 复制代码
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        table=collections.defaultdict(list)
        for str in strs:
            table[''.join(sorted(str))].append(str)
        return list(table.values())

128.最长连续序列

题目 :给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

  • 构造集合,时间复杂度是o(n)
  • 找最小的数,然后一直遍历找到当前连续数的最大值
python 复制代码
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        # 构造集合,找最小的数
        nums=set(nums)#时间复杂度是o(n),遍历整个数组
        maxlen=0
        for num in nums:
            if num-1 not in nums:#找最小的数
                current_num=num
                current_long=1
                while current_num+1 in nums:
                    current_num=current_num+1
                    current_long+=1
                maxlen=max(maxlen,current_long)
        return maxlen  
相关推荐
阿维的博客日记12 小时前
LeetCode 139. 单词拆分 - 动态规划解法详解
leetcode·动态规划·代理模式
程序员Xu13 小时前
【LeetCode热题100道笔记】二叉树的右视图
笔记·算法·leetcode
笑脸惹桃花13 小时前
50系显卡训练深度学习YOLO等算法报错的解决方法
深度学习·算法·yolo·torch·cuda
阿维的博客日记13 小时前
LeetCode 48 - 旋转图像算法详解(全网最优雅的Java算法
算法·leetcode
GEO_YScsn14 小时前
Rust 的生命周期与借用检查:安全性深度保障的基石
网络·算法
程序员Xu14 小时前
【LeetCode热题100道笔记】二叉搜索树中第 K 小的元素
笔记·算法·leetcode
THMAIL15 小时前
机器学习从入门到精通 - 数据预处理实战秘籍:清洗、转换与特征工程入门
人工智能·python·算法·机器学习·数据挖掘·逻辑回归
Kevinhbr15 小时前
CSP-J/S IS COMING
数据结构·c++·算法
蕓晨15 小时前
set的插入和pair的用法
c++·算法
THMAIL16 小时前
深度学习从入门到精通 - AutoML与神经网络搜索(NAS):自动化模型设计未来
人工智能·python·深度学习·神经网络·算法·机器学习·逻辑回归