题目:给定一个整数数组nums 和一个目标值target,在nums中找到和为目标值的两个整数,并返回它们的数组下标
solution 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)-1):
for j in range(i+1,len(nums)):
if nums[i]+nums[j] == target:
return i,j
solution 2:采用字典的方法模拟哈希表(这里我也不清楚什么是哈希表)
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
index_dict = {}
for inx,num in enumerate(nums):
if (target-num) in index_dict:
return index_dict[target-num],inx
index_dict[num] = inx
相比第一种方法,这里的第二种方法时间上块了很多。另外一种解法是先遍历一遍整个数组然后,然后在字典里直接遍历。