【力扣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的键集合

相关推荐
phltxy6 小时前
C语言操作符详解
java·c语言·算法
aqiu1111117 小时前
【LeetCode 902】最大为 N 的数字组合 - 详细题解与数位组合思路
数据结构·算法·leetcode·蓝桥杯·数位dp
辰烨chenye7 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
罗西的思考8 小时前
DreamZero 与 DreamDojo:世界模型与策略的分层协同综合分析与对比
人工智能·算法·机器学习
玖玥拾8 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表
知无不研9 小时前
c语言中循环的介绍与简单应用
c语言·开发语言·算法·循环·for·while
a1879272183110 小时前
【算法】动态规划第四篇:背包收官——min 哨兵、计数世界与组合排列分水岭
算法·leetcode·动态规划·dp·01背包·算法讲解·决策合并
2601_9622974811 小时前
在python3中、下列输出变量a的正确写法是_2020超星大数据Python免费答案
数据结构·python·算法·编程·字符串操作
辰烨chenye11 小时前
LeetCode Hot 100 题解 · 子串篇
算法·leetcode·职场和发展