Leetcode:两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
第一种方法:
- 我先遍历两次,然后为了防止重复使用数字,判断下标是否相等,如果不相等在返回。虽然这个方法行得通,但是非常耗时间! 不推荐此方法!!!
nums = [2, 7, 11, 15]
target = 9
def answer(nums, target):
for index, num in enumerate(nums):
for other_index, other_num in enumerate(nums):
if other_num == target - num:
# 防止重复使用
if index != other_index:
return index, other_index
a = answer(nums, target)
print(a)
第二种方法:
- 这个方法是先定义一个空列表,在遍历原有列表,把遍历的下标和值加进空列表,从里面找匹配的! 这个方法比第一种方法好!
nums = [2, 7, 11, 15]
target = 9
def answer(nums, target):
n_list = []
for index, num in enumerate(nums):
another_num = target - num
if another_num in n_list:
return n_list.index(another_num), index
n_list.append(num)
return None
a = answer(nums, target)
print(a)
(推荐)第三种方法:
- 先定义一个字典,在遍历列表,把遍历的下标和值加进字典,从字典里面找答案!
nums = [2, 7, 11, 15]
target = 9
def answer(nums, target):
# 创建一个字典,每次把遍历的数字加进去
another_nums = {}
# 利用enumerate,把索引和值遍历出来
for index, num in enumerate(nums):
another_num = target - num
if another_num in another_nums:
return another_nums[another_num], index
another_nums[num] = index
return None
a = answer(nums, target)
print(a)