【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
相关推荐
不会就选b5 小时前
算法日常・每日刷题--<贪心>14
算法
mmmmath_38 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z8 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
醇氧9 小时前
MySQL 8.0 系统表损坏与引擎转换故障排查实战
数据结构·算法
大熊背9 小时前
《Color constancy by characterization of illumination chromaticity》之色度色域最大化算法(二)
算法·白平衡·色度·色温
钓鱼的肝9 小时前
梳理(1-5)
c++·经验分享·笔记·算法·青少年编程
HZZD_HZZD10 小时前
CSDN_批发市场水电漏损归因算法LAM的原理与落地
嵌入式硬件·物联网·算法
shirsl11 小时前
算法 Day 5 树 / 二叉树 + DFS
数据结构·python·算法
木子算法12 小时前
非凸、离散、还耦合:论文里的求解方法是一条四步流水线
人工智能·算法·目标跟踪