难度: Easygit
刷题内容 原题链接leetcode-twosumgithub
内容描述apache
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.bash
Example:函数
Given nums = [2, 7, 11, 15], target = 9,ui
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].spa
1.两个总和 简单 给定一个整数数组,返回两个数字的索引,使它们相加到特定目标。翻译
您能够假设每一个输入只有一个解决方案,而且您可能不会两次使用相同的元素。code
例:
被给NUMS = [2,7,11,15],目标变量TARGET = 9,
由于NUMS[0] + NUMS[1] = 2 + 7 = 9,
则返回[0,1]。
思路一:最直接想到的就是分别线性遍历一遍,不过期间复杂度: O(N^2)- 空间复杂度: O(1)******
class Solution(object):
def twoSum(self, nums, target):
""" :type nums: List[int] :type target: int :rtype: List[int] """
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
复制代码
很显然上面对时间要求太多,能够牺牲空间换时间
思路二:时间复杂度: O(N)- 空间复杂度: O(N)******
class Solution(object):
def twoSum(self, nums, target):
""" :type nums: List[int] :type target: int :rtype: List[int] """
lookup = {}
for i, num in enumerate(nums):
if target - num in lookup:
return [lookup[target-num], i]
else:
lookup[num] = i
复制代码
class Solution(object):
def twoSum(self, nums, target):
""" :type nums: List[int] :type target: int :rtype: List[int] """
lookup = {}
for i, num in enumerate(nums):
print("序号变量i :{i} 数值变量num :{num}".format(i=i,num=num))
if target - num in lookup:
print("返回找到的两个数的索引值列表:{}".format([lookup[target-num], i]))
else:
lookup[num] = i
print("字典lookup:{}".format(lookup))
S = Solution()
nums = [2,7,13,11]
target = 9
S.twoSum(nums,target)
# 如下是 enumerate() 方法的语法:
#
# enumerate(sequence, [start=0])
# 参数
# sequence -- 一个序列、迭代器或其余支持迭代对象。
# start -- 下标起始位置。
# 返回值
# 返回 enumerate(枚举) 对象。
#
# 实例
# 如下展现了使用 enumerate() 方法的实例:
#
# >>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
# >>> list(enumerate(seasons))
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
# >>> list(enumerate(seasons, start=1)) # 下标从 1 开始
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
复制代码