# 两数之和
# 给定一个整数数组nums,和一个目标值target,在该数组中找出和为目标值的那两个整数,并返回他们的数组下标
'''# 暴力遍历
def TwoSum(nums, target):
for i in range(len(nums)):
temp = target - nums[i]
if temp in nums[i + 1:]:
j = nums.index(temp, i + 1)
return [i, j]'''
'''#排序+首尾查询
def TwoSum(nums, target):
sort_id = sorted(range(len(nums)), key=lambda x: nums[x])
# 记录排序后的位置索引
left = 0 # sort_id的第一个值
right = len(nums) - 1 # sort_id的最后一个值
while left < right:
s = nums[sort_id[left]] + nums[sort_id[right]]
if s == target:
return [sort_id[left], sort_id[right]]
elif s < target:
left += 1
else:
right -= 1'''
def TwoSum(nums, target):
buff = {}
for i, v in enumerate(nums):
temp = target - v
if temp in buff:
return [buff.get(temp), i] # buff存放了0到i-1的v:i
else:
buff[v] = i # 存放value:id
# nums = [2, 3, 5, 7, 8]
nums = [4, 0, 4]
# nums = [-1, -2, -3, -4, -4]
target = 8
print(TwoSum(nums, target))