- Two Sum
地址:https://leetcode.com/problems/two-sum/#/description
Python
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
return_list = []
#dict = {}
for i in range(0,len(nums)):
#list = []
for j in range(i+1,len(nums)):
#print i,j
temp = nums[i]+nums[j]
if temp == target:
return [i,j]
#print return_list
#return return_list
用了双循环,时间复杂度肯定是O(n^2)还是比较复杂的,看看别人的参考a Python solution in O(n) time:
https://leetcode.com/problems/two-sum/#/solutions
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
每遍历一个数,把target减去该数的值存入buff_dict中,如果在接下来的数中有,直接返回两数index