给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码解析
class Solution:
def twoSum(self, nums, target):
"""
函数参数1 nums: List[int]
函数参数2 target: int
函数返回值: List[int]
"""
# sorted(iterable, cmp=None, key=None, reverse=False) 可以对所有可迭代的对象进行排序操作。
'''
iterable -- 可迭代对象。
cmp -- 比较的函数,这个具有两个参数,参数的值都是从可迭代对象中取出,此函数必须遵守的规则为,大于则返回1,小于则返回-1,等于则返回0。
key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
'''
# range() 函数可创建一个整数列表
# 1.创建索引列表
sorted_id = sorted(range(len(nums)), key=lambda k: nums[k])
print(type(sorted_id))
print(sorted_id)
# 2.头部索引
head = 0
# 3.尾部索引
tail = len(nums) - 1
# 4.按索引取整数列表值相加
sum_result = nums[sorted_id[head]] + nums[sorted_id[tail]]
print("sorted_id[{0}] = {1}; sorted_id[{2}] = {3} sum_result = {4}".format(head, sorted_id[head], tail, sorted_id[tail], sum_result))
# 5.与目标值相比较,循环对比查询
while sum_result != target:
if sum_result > target:
tail -= 1
elif sum_result < target:
head += 1
sum_result = nums[sorted_id[head]] + nums[sorted_id[tail]]
print("sorted_id[{0}] = {1}; sorted_id[{2}] = {3} sum_result = {4}".format(head, sorted_id[head], tail, sorted_id[tail], sum_result))
# 6.返回最终结果
return [sorted_id[head], sorted_id[tail]]
if __name__ == '__main__':
solu = Solution()
nums = [2, 7, 11, 15]
print(solu.twoSum(nums, 9))
class Solution:
def twoSum(self, nums, target):
"""
:param nums: 整数数组
:param target: 目标值
:return: 返回结果列表
"""
# enumerate(sequence, [start=0]) 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
# sequence -- 一个序列、迭代器或其他支持迭代对象。
# start -- 下标起始位置。
# 1.创建字典临时变量
hashmap = {}
# 2.将列表的数据和数据下标一起遍历
for index, num in enumerate(nums):
# 3.获取数据和目标数据的差值
another_num = target - num
print("num={0} target={1} another_num={2} hashmap={3}".format(num, target, another_num, hashmap))
# 4.判断差值是否存在于字典中
if another_num in hashmap:
# 5.如果存在返回字典坐标和当前坐标
return [hashmap[another_num], index]
# 6.将列表数据和下标暂存入字典
hashmap[num] = index
# 7.没查询到返回为空
return None
if __name__ == '__main__':
solu = Solution()
print(solu.twoSum([2, 10, 11, 13, 7], 9))