最近在看《数学好的人是如何思考的》,找道算法题练练。
题目:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
运行环境:mac 16G , 2.2Gz 四核 intel core i7
# Q: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
def solution(nums, target):
"""
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
:param nums: 给定的整数数组;
:param target: 给定的目标值;
:return : 求的的元素在数组中下标
"""
dict1 = {}
list1 = []
for i in range(0, len(nums)):
num = target - nums[i]
# 字典中查找的时间复杂度为O(1),因此总时间复杂度为O(n)
if num not in dict1:
dict1[nums[i]] = i
else:
list1.append([dict1[num], i])
return list1
def main():
nums = [1, 2, 3, 4, 5, 6, 7]
target = 9
print(solution(nums, target))
main()运行结果:
[[3, 4], [2, 5], [1, 6]]
spend time:4.7e-05 s