1. Two Sum
problem
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
solution
- 大致思路
- target减去每个元素=y
- 判断y是否在序列里,是的话返回两个元素下标
- 特殊情况有两点
- 例如[5,3,7],10 不能5+5=10;这一点用倒序pop移除元素
- 例如[5,3,5],10 两个5的index要区分;这一点,第二个元素采用长度-倒序元素位置=正序元素位置(刚好上一点pop已经对list倒序了)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
listNum = []
mid = nums[::-1]
for index,x in enumerate(nums):
y = target - x
mid.pop()
if y in mid:
listNum.append(index)
listNum.append(len(nums)-1-mid.index(y))
return listNum
- 遍历O(n)内嵌套了in O(n);
discuss
class Solution(object):
def twoSum(self, nums, target):
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(nums)):
if nums[i] in buff_dict:
return [buff_dict[nums[i]], i]
else:
buff_dict[target - nums[i]] = i
-
大方向类似,逻辑更清晰一点,dict取元素的平均复杂度是O(1)
-
else里面往字典里储存的是{差值:当前元素index}; 当某元素等于差值时,返回[之前储存的index,某元素index]

浙公网安备 33010602011771号