Leetcode算法题库Python版本题目1-两数之和
题目:
给定一个整数数列,找出其中和为特定值的那两个数。
你可以假设每个输入都只会有一种答案,同样的元素不能被重用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
解答1:
1 nums = [2, 7, 11, 15] 2 target = 9 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: List[int] 7 """ 8 #用len()方法取得nums列表长度 9 n = len(nums) 10 #x从0到n取值(不包括n) 11 for x in range(n): 12 a = target - nums[x] 13 #用in关键字查询nums列表中是否有a 14 if a in nums: 15 #用index函数取得a的值在nums列表中的索引 16 y = nums.index(a) 17 #假如x=y,那么就跳过,否则输出x,y 18 if x == y: 19 continue 20 else: 21 print([x,y]) 22 break 23 else : 24 continue
输出:
[0, 1]