【力扣100】1.两数之和__231206

两数之和

第一次题解:

python 复制代码
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        #思路是for循环第一个数然后在数组中找差值
        for i in range(0,len(nums)-1):
            second_value=target-nums[i]
            for j in range(i+1,len(nums)):
                if nums[j]==second_value:
                    return [i,j]

思路:两个for循环,找元素

还有一种方法:

python 复制代码
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        n = len(nums)
        for i in range(0,n):
            for j in range(i+1,n):
                if nums[i] + nums[j] == target:
                    return [i, j]

也是两层for循环


使用哈希表解法:

python 复制代码
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashtable={}
        for index,value in enumerate(nums):
            # in hashtable 判断的是键集合
            if target-value not in hashtable:
                # 因为本题返回下标,所以键放数值,值放下标
                hashtable[value]=index
            else:
                return [hashtable[target-value],index]

时间复杂度:n

这里有两个要注意的点:

1.enumerate():

返回可迭代的index和values

可以使用enumerate的是:列表,元组和字符串

2. x in hashtable:

这里比较的是x是不是在hashtable的键集合

相关推荐
古城小栈1 天前
为啥说:训练用BF16,推理用FP16
人工智能·算法·机器学习
KaMeidebaby1 天前
卡梅德生物技术快报|蛋白 N 端测序在重组贻贝融合蛋白表征中的应用,解决原核表达序列偏移工艺难题
前端·人工智能·物联网·算法·百度
Turbo正则1 天前
群论在AI中的应用概述
人工智能·算法·抽象代数
ysa0510301 天前
【并查集】判环
c++·笔记·算法
Jerry1 天前
KeetCode 44. 开发商购买土地
算法
Jerry1 天前
KeetCode 58. 区间和
算法
Jerry1 天前
LeetCode 209. 长度最小的子数组
算法
彦为君1 天前
算法思维与经典智力题
java·前端·redis·算法
智能优化与强化学习1 天前
Gym(Gymnasium)仿真环境详解(二):环境简介、入门算法、调参要点、核心挑战
算法·强化学习·gym·零基础入门·算法评估
mxwin1 天前
Unity Shader exp 函数的算法与渲染应用
算法·unity·游戏引擎·shader