给定一个整数数组 nums
和一个目标值 target
,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
刚开始拿python试手,也是不熟悉,这道题用两种思路做,一种常规的解法,一种python中的字典也就想当于哈希表
一、常规解法
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(0,len(nums)-1):
for j in range(i+1,len(nums)):
if nums[i]+nums[j] == target:
return [i,j]
这种解法较为常规,也是很多人首先想到的,但是时间复杂度很大
二、字典解法
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# for i in range(0,len(nums)-1):
# for j in range(i+1,len(nums)):
# if nums[i]+nums[j] == target:
# return [i,j]
dict_num = {}
for i in range(0,len(nums)):
j = target - nums[i]
if j not in dict_num:
dict_num[nums[i]] = i
else:
return [dict_num[j],i]
这种解法说实话我是真没想到,是看了别人的解法后自己再看一遍最后写的,这里我写下作者的大概思路。
首先利用字典的存储结构缩短时间复杂度,最后将列表中其中一解的索引存入字典中的value,而将key中存的却是列表的值,到了最后如果查找到了相应的值,就做相应的返回,设计的很精妙!
根据这道题,改编一下,如果将题目中的两个值,变成三个值??那有该怎么解答呢?