给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# 1.暴力法
n=len(nums)
for i in range(n-1):
for j in range(i+1, n):
if nums[i] + nums[j] == target:
return [i,j]
return []
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# 2.Hash Table
"""
用暴力法解题时,时间复杂度为O(N^2),寻找target-x的时间复杂度高。利用哈希表来查询,
哈希表可以根据哈希算法直接查找,时间复杂度为O(1)。
因为题目要求返回index,所以可以将nums中的值作为key,将index作为value。
"""
n = len(nums)
hashT = {}
# 先将nums的数据都放到哈希表中
for i,val in enumerate(nums):
hashT[val] = i
for i in range(n):
diff = target - nums[i]
# 这里不止要判断是否存在这个值,而且要保证同一个元素不能重复出现,所以添加了and后面的判断
if diff in hashT and hashT[diff] != i:
return [i, hashT[target-nums[i]]]
return []
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# 3.官方哈希表解法,代码更加简洁
hashT = dict() # python的内置函数,创建一个空的字典,我们用字典来实现哈希表
for i,val in enumerate(nums):
# 这里先判断哈希表中是否存在target-x,这样可以避免同一个元素重复使用,这一步真是太好了,先判断,然后放入到哈希表中
if target - val in hashT:
return [i, hashT[target-val]]
hashT[val] = i
return []