【HOT100】DAY1

两数之和

哈希,不在哈希表就先存起来

python 复制代码
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hash_map = {}
        for idx, num in enumerate(nums):
            a = target - num
            if a in hash_map:
                return [hash_map[a], idx]
            hash_map[num] = idx
        return []

字母异位词分组

哈希,用排序后的字符串作分类指标

"".join(sorted(s)):先将s转换成字符列表并排序,之后数据类型转回字符串,作为key

python 复制代码
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        from collections import defaultdict

        hash_map = defaultdict(list)
        for s in strs:
            key = "".join(sorted(s))
            hash_map[key].append(s)
        return list(hash_map.values())

最长连续序列

if num - 1 not in num_set:集合中搜索,集合原生支持 x in s,平均时间复杂度 O(1)

python 复制代码
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        num_set = set(nums)
        max_length = 0
        for num in num_set:
            if num - 1 not in num_set:
                current_num = num
                current_length = 1
                while current_num + 1 in num_set:
                    current_num += 1
                    current_length += 1
                max_length = max(max_length, current_length)
        return max_length

移动零

前指针自循环,若不指向0则后指针跟着前指针走,若指向0则后指针不动,等到前指针不指向0了,再将0换到后面。像一个会"收集0"的滑动窗口,等前指针到头了,则0也收集完了。

python 复制代码
class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        j = 0
        for i in range(len(nums)):
            if nums[i] != 0:
                nums[i], nums[j] = nums[j], nums[i]
                j += 1
相关推荐
CS_Zero1 小时前
无人机路径规划算法——EGO-planner建模总结—— EGO-planner 论文笔记(一)
论文阅读·算法·无人机
杰梵1 小时前
聚酯切片DSC热分析应用报告
人工智能·算法
@BangBang1 小时前
leetcode (4): 连通域/岛屿问题
算法·leetcode·深度优先
Ulyanov1 小时前
像素迷宫:路径规划算法的可视化与实战
大数据·开发语言·python·算法
Mr_pyx2 小时前
【LeetCode Hot 100】 除自身以外数组的乘积(238题)多解法详解
算法·leetcode·职场和发展
Trouvaille ~2 小时前
零基础入门 LangChain 与 LangGraph(五):核心组件上篇——消息、提示词模板、少样本与输出解析
人工智能·算法·langchain·prompt·输入输出·ai应用·langgraph
MOON404☾2 小时前
Chapter 002. 线性回归
算法·回归·线性回归
故事和你912 小时前
洛谷-数据结构-1-3-集合3
数据结构·c++·算法·leetcode·贪心算法·动态规划·图论
春栀怡铃声3 小时前
【C++修仙录02】筑基篇:类和对象(上)
开发语言·c++·算法
ulias2123 小时前
leetcode热题 - 3
c++·算法·leetcode·职场和发展