hot100 python解法合集

1. 两数之和

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

49. 字母异位词分组

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

128. 最长连续序列

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

核心:使用**哈希集合(HashSet)**来通过空间换时间。

时间复杂度:

O(n)

外层的 for 循环遍历集合中的每个元素。

关键在于 if num - 1 not in num_set 这个判断。这意味着内部的 while 循环只有在找到序列起点时才会执行。

例如对于序列 [1, 2, 3, 4]:

遍历到 2:2-1=1 存在,跳过。

遍历到 3:3-1=2 存在,跳过。

遍历到 4:4-1=3 存在,跳过。

只有遍历到 1 时:1-1=0 不存在,进入 while 循环,访问 2, 3, 4。

因此,数组中的每个数字,最多只会被访问两次(一次是在 for 循环中,一次是在 while 循环中作为后续数字被检查)。所以总操作次数是线性的

283. 移动零

python 复制代码
class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        i, j = 0, 0
        for i in range(len(nums)):
            if nums[i] != 0:
                if i > j:
                    nums[j], nums[i] = nums[i], nums[j]
                j += 1
        

11. 盛最多水的容器

python 复制代码
class Solution:
    def maxArea(self, height: List[int]) -> int:
        max_val = 0
        left, right = 0, len(height) - 1
        while left < right:
            cur_val = min(height[left], height[right]) * (right - left)
            if cur_val > max_val:
                max_val = cur_val
            if height[left] < height[right]:
                left += 1
            else:
                right -= 1
        return max_val

15. 三数之和

python 复制代码
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)
        res = []

        nums.sort()
        for i in range(n):
            if nums[i] > 0:
                break
            if i > 0 and nums[i] == nums[i - 1]:
                continue

            left = i + 1
            right = n - 1
            while left < right:
                total = nums[i] + nums[left] + nums[right]
                if total == 0:
                    res.append([nums[i], nums[left], nums[right]])
                    while left < right and nums[left + 1] == nums[left]:
                        left += 1
                    while left < right and nums[right - 1] == nums[right]:
                        right -= 1
                    left += 1
                    right -= 1
                elif total > 0:
                    right -= 1
                else:
                    left += 1
        return res
相关推荐
unicrom_深圳市由你创科技4 分钟前
做虚拟示波器这种实时波形显示的上位机,用什么语言?
c++·python·c#
小敬爱吃饭4 分钟前
Ragflow Docker部署及问题解决方案(界面为Welcome to nginx,ragflow上传文件失败,Docker中的ragflow-cpu-1一直重启)
人工智能·python·nginx·docker·语言模型·容器·数据挖掘
无限进步_10 分钟前
【C++】电话号码的字母组合:从有限处理到通用解法
开发语言·c++·ide·windows·git·github·visual studio
宸津-代码粉碎机10 分钟前
Spring Boot 4.0虚拟线程实战调优技巧,最大化发挥并发优势
java·人工智能·spring boot·后端·python
JJay.24 分钟前
Android Kotlin 协程使用指南
android·开发语言·kotlin
知行合一。。。29 分钟前
Python--04--数据容器(集合)
python
csbysj202030 分钟前
jQuery 捕获详解
开发语言
C++ 老炮儿的技术栈39 分钟前
GCC编译时无法向/tmp 目录写入临时汇编文件,因为设备空间不足,解决
linux·运维·开发语言·汇编·c++·git·qt
Captain_Data41 分钟前
Python机器学习sklearn线性模型完整指南:LinearRegression/Ridge/Lasso详细代码注释
python·机器学习·数据分析·线性回归·sklearn
爱码小白44 分钟前
MySQL 单表查询练习题汇总
数据库·python·算法