Problem Description:
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
题目要求输出相加值为给定target的两个元素在List中的下标。
思路一:
两重循环,遍历给定List中两两相加的每一种结果,如和target数目相同则输出下标。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
rtype = []
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
rtype.append(i)
rtype.append(j)
return rtype
但这样做会导致时间复杂度太大。
思路二:
换个思路,因target给定,那么对于一次遍历中需要寻找的就是target - 当前数的数值是否出现在这个List中。
则可以用一个空字典存放遍历过的元素,字典中的键对应的是原列表中的数值,字典中的值对应原列表中的下标。
每次我们都判断一下列表中的元素的“target - 元素值”是否在字典中。如果在,只需返回这两个元素的下表即可;如果不在,就把该元素加入到字典中,供后面的元素对比。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
rtype = {}
for i in range(len(nums)):
if target - nums[i] in rtype:
return [rtype[target - nums[i]], i]
if nums[i] not in rtype:
rtype[nums[i]] = i
时间复杂度大大降低。