Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. |
1.暴力破解,时间复杂度为
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
size = len(nums)
for i in range(size):
for j in range(i + 1, size):
if nums[i] + nums[j] == target:
return [i, j]
2.使用字典dict,时间复杂度为,执行2次迭代的字典
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
index = 0
numDict = {}
for e in nums:
numDict[e] = index
index += 1
for i in range(len(nums)):
otherNum = target - nums[i]
if otherNum in numDict.keys() and numDict[otherNum] != i:
return [i, numDict[otherNum]]
3.使用字典dict,时间复杂度为,执行1次迭代的字典
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
numDict = {}
for i in range(len(nums)):
otherNum = target - nums[i]
if otherNum in numDict.keys() and numDict[otherNum] != i:
return [i, numDict[otherNum]]
numDict[nums[i]] = i
总结:
1.最开始使用的是暴力破解的方法, 遇到的问题是range()方法使用错误,导致出现一次提交错误。range(i, j),表示生成i<=N<j之间的一组整数,此题的一对解[i, j]中i与j是不同的,即不能使用num[i]本身构成解,后面两种使用字典dict出错也是因为未考虑这点。
2.使用字典时未考虑num[i]与num[j]相同的情况,但是因为在使用方法2时,直接通过,所以在实现方法3时出现问题。字典中键值相同时会更新为最新出现的值。例如nums = [3, 3],target = 6,在使用方法2构造dict时,numDict[3] = 1,因此当num[0] 时另一个数otherNum = 3,求得索引index = 1,这样就构成了解,因此也忽略了当存在值相同的情况。使用方法3时,因为采用一次迭代,所以需要边插值,边解另一个值otherNum,在第一次实现这个算法时,我先将值更新到字典中,导致当nums = [3, 3]时,因为numDict[3] = 1 = i,所以出现返回值为NULL的情况,出现错误,正确的做法是先检查otherNum是否存在于字典中,然后再进行插值,这样当i = 1时,numDict[3] = 0,避免出错。因为此题考虑的只有一组正确解,因此这样做是没有问题的。当存在多个解时,如nums = [3, 3, 3],方法2返回的是[0, 2],方法3返回的是[1, 0]。