python 练习题 俩数之和

学习地址:

https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x2jrse/

 1 '''
 2 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。
 3 
 4 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
 5 
 6 你可以按任意顺序返回答案。
 7 
 8  
 9 
10 示例 1:
11 
12 输入:nums = [2,7,11,15], target = 9
13 输出:[0,1]
14 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
15 示例 2:
16 
17 输入:nums = [3,2,4], target = 6
18 输出:[1,2]
19 示例 3:
20 
21 输入:nums = [3,3], target = 6
22 输出:[0,1]
23 
24 
25 
26 '''
27 
28 #方法一
29 
30 class Solution:
31     def twoSum(self, nums: List[int], target: int) -> List[int]:
32         l = len(nums)
33         res=[]
34         for i in range(l):
35             num = target -nums[i]
36             if num in nums[i+1:]:
37                 res.append(i)
38                #避免重复,找到的索引下标是第一个
39                 numIndex = nums.index(num) if nums[i] != num else nums[i+1:].index(num)+i+1
40                 res.append(numIndex)
41                 break
42         return res
43 
44 #方法二,力扣上的写法
45 class Solution:
46     def twoSum(self, nums: List[int], target: int) -> List[int]:
47         dict_num = dict()
48         for i, v in enumerate(nums):
49             tmp = target - v
50             if dict_num.get(tmp) is not None:
51                 return i, dict_num[tmp]
52             else:
53                 dict_num[v] = i
54         return 0, 0

作者:xuanli
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x2jrse/?discussion=f9AJO8
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

原文地址:https://www.cnblogs.com/whycai/p/15220583.html