001-力扣刷题1--两数之和
题目描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 力扣不用进行实例化:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dict1={} #将数字与索引一一对应 for i,num in enumerate(nums): if target -num in dict1: #如果目标数减去num的数在字典里的话说明这两个数相加是等于target的 return [dict1[target-num],i] #返回存放 else : dict1[num] = i |
自己在编译器中进行测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | # -*- coding: utf-8 -*- """ Created on Tue Apr 30 09:47:46 2019 @author: zangz """ class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dict1={} #将数字与索引一一对应(存放的是那些for循环中筛选出来的第一个数和不是的数) for i,num in enumerate(nums): if target -num in dict1: #如果目标数减去num的数在字典里的话说明这两个数相加是等于target的 return [dict1[target-num],i] #返回存放第一个数及第二个数的索引 else : dict1[num] = i """ 思路就是创建一个字典用来存储第一个数及其索引,这个字典存储的是两个数中的第一个数以及其他相加不等于target的数 使用if筛选出第二个数,因为第一个数没有通过if条件,因此经过了else添加将第一个数存到了字典中,这时候第二个字来的时候呢 就会通过筛选的添加,得到第二个数的索引. 因此返回值只要取出字典中对应的第一个数的对应的索引.以及第二个数对应的索引就可以了 但是缺陷就是通过返回值,只能返回一组,如果有两组就无能为力了. """ #下面进行测试 nums=[2,7,11,15] target=9 s = Solution() jie_guo=s.twoSum(nums,target) print(jie_guo) |
执行结果:
1 | [0, 1] |
下面进行改进,如果有多组怎么办?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | # -*- coding: utf-8 -*- """ Created on Tue Apr 30 09:47:46 2019 @author: zangz """ class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dict1={} #将数字与索引一一对应(存放的是那些for循环中筛选出来的第一个数和不是的数) list1=[]#定义一个列表用来存储多组值 for i,num in enumerate(nums): if target -num in dict1: #如果目标数减去num的数在字典里的话说明这两个数相加是等于target的 list1.append([dict1[target-num],i]) #返回存放第一个数及第二个数的索引 else : dict1[num] = i return list1 """ 在上一个程序的基础上添加一个列表用来接收多组的索引,这样就可以将所有的情况用一个二维的列表记录下来了 """ #下面进行测试 nums=[2,7,11,15,3,6,4,5] target=9 s = Solution() jie_guo=s.twoSum(nums,target) print(jie_guo) |
执行结果:
1 | [[0, 1], [4, 5], [6, 7]] |