1.循环遍历求解
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
leng = len(nums)
for i in range(leng):
nums2 = target - nums[i]
if nums2 in nums[i+1:]:
return [i,nums[i+1:].index(nums2)+i+1]
从第一个元素开始遍历,然后查看target-nums元素是否在剩下的元素里,如果有返回索引值。
len():返回对象长度或个数。
list.index(obj):用于返回列表中某个obj第一个匹配项的索引值。该方法返回查找对象的索引位置,如果没有找到对象则抛出异常。
range(start, stop[, step]):创建一个整数列表,一般用于for循环中。可以用于重复打印。
for i in range(3):
print('加油,你可以的!!!')
>>>加油,你可以的!!!
>>>加油,你可以的!!!
>>>加油,你可以的!!!
2.哈希表
建立一个哈希表,对于每一个 x
,我们首先查询哈希表中是否存在 target - x
,存在返回索引值,不存在将 x
插入到哈希表中,即可保证不会让 x
和自己匹配。
不需要遍历两遍,一边查询一边建表。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashtable = dict()
for i, num in enumerate(nums):
if target - num in hashtable:
return [i, hashtable[target-num]]
hashtable[nums[i]] = i
enumerate(sequence, [start=0]):将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
哈希表用时仅32ms, 循环遍历勇士316ms,将近10倍,但是哈希表占内存大,用空间换时间。