LeetCode热题100-两数之和

Python3实现:

  • 暴力解法:时间复杂度n2,空间复杂度1
python 复制代码
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        if not nums and len(nums) > 2:
            raise Exception("输入数据格式有误!")
        length = len(nums)
        for i, num in enumerate(nums):
            for j in  range(i + 1, length):
                if nums[i] + nums[j] == target:
                    return [i, j]
        return []

关注点:range为左闭右开,enumerate可以设定索引开始值。

  • hash方法:时间复杂度n,空间复杂度n
python 复制代码
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        if not nums and len(nums) > 2:
            raise Exception("输入数据格式有误!")
        des_dict = {}
        for i in range(len(nums)):
            dif = target - nums[i]
            if dif in des_dict.keys():
                return [des_dict[dif], i]
            des_dict[nums[i]] = i
        return []   

这种算是哈希表的变形实现,使用了字典当作hash表。

相关推荐
一只齐刘海的猫1 天前
【Leetcode】找到字符串中所有字母异位词
算法·leetcode·职场和发展
海清河晏1111 天前
数据结构 | 八大排序
数据结构·算法·排序算法
IronMurphy1 天前
【算法五十七】146. LRU 缓存
算法·缓存
文艺倾年1 天前
【强化学习】强化学习基本概念,20W字总结(一)
人工智能·python·语言模型·自然语言处理·面试·职场和发展·大模型
凌波粒1 天前
LeetCode--108.将有序数组转换为二叉搜索树(二叉树)
算法·leetcode·职场和发展
liulilittle1 天前
KCC:在 BBR 思路上的一次探索
网络·tcp/ip·算法·bbr·通信·拥塞控制·kcc
浦信仿真大讲堂1 天前
达索系统SIMULIA Abaqus 2026接触和约束的增强新功能介绍
人工智能·python·算法·仿真软件·达索软件
点云侠1 天前
PCL 生成三棱锥点云
c++·算法·最小二乘法
兰令水1 天前
leecodecode【面试150】【2026.6.13打卡-java版本】
java·算法·leetcode
临沂堇1 天前
刷题日志 | Leetcode Hot 100 哈希
算法·leetcode·哈希算法