- 题目:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
- 示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
- 刷题笔记
思路一:
首先是第一次做题,没有奇技淫巧,当时直接用暴力破解法
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for each in range(0,len(nums)-1):
for each2 in range(each+1,len(nums)):
if nums[each]+nums[each2]==target:
return each,each2
在测试的时候通过,但是提交时超出时间限制而不通过,显然这种方法效率不行。故舍之
(在C语言中暴力破解法效率高,能通过)
思路二:
通过字典方法查找键值。
因为当列表为空时嵌套的for没有找到数值。所以d[i] = item这句应该放在嵌套for后面
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i, item in enumerate(nums):
temp = target - item
for key,value in d.items():
if temp == value:
return key,i
d[i] = item
return None
编译通过!执行用时 2084 ms
思路三:
通过python自带的列表寻找位置函数 index() 解题
注意 index() 没有找到数值时会出错。
index()方法语法:
str.index(str, beg=0, end=len(string))
代码:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
temp = target - nums[i]
try:
i2 = nums.index(temp,i)
if i!=i2:
return i,i2
except:
pass
return None
编译通过,用时1468 ms。