leetcode之两数之和(Python)

tech2026-03-10  0

题目描述

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]

1.暴力解法

直接用双指针遍历数组。时间复杂度 O ( n 2 ) O(n^2) O(n2),空间复杂度 O ( 1 ) O(1) O(1)

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

2.hash

关键是使用Python的字典,从头遍历数组,查询字典中是否已经存在与当前元素的和为target的键,如果存在就返回结果;否则将当前元素作为键,元素索引作为值存入字典,继续遍历。时间复杂度 O ( n ) O(n) O(n),空间复杂度 O ( n ) O(n) O(n)

class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hashset={} for i in range(len(nums)): if hashset.get(target - nums[i]) is not None: return [hashset.get(target - nums[i]), i] hashset[nums[i]] = i

思考

如果数组中同一个元素可以使用两遍,如何用hash? 遍历两次数组
最新回复(0)