【题目描述】

【方法一】:暴力法
循环套循环,一个个遍历知道找到 i+j = target
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in nums:
for j in nums:
if(i+j == target && i != j):
a = nums.index(i)
b = nums.index(j)
return [a,b]
#疑问# 在这里如果直接返回[nums.index(i),nums.index(j)]就会报错。
【方法二】:判断target - i 是否在序列中,这种。
def twoSum(nums, target):
for i in range(len(nums)):
b = target - nums[i]
if b in nums[i:] and b!= nums[i]:
print([i,nums.index(b)])
break
【方法三】:用哈希表(Hash table),用(key - value)使下标和其对应元素可以。

本文介绍了使用Python解决LeetCode问题的方法,包括暴力遍历、判断目标减元素是否存在序列以及利用哈希表优化查找。特别提到在使用哈希表时,通过(key-value)形式加速下标和元素的匹配,避免了重复计算。
最低0.47元/天 解锁文章
360

被折叠的 条评论
为什么被折叠?



