leetcode1 twoSum

 1 """
 2 Given an array of integers, return indices of the two numbers such that they add up to a specific target.
 3 
 4 You may assume that each input would have exactly one solution, and you may not use the same element twice.
 5 
 6 Example:
 7 
 8 Given nums = [2, 7, 11, 15], target = 9,
 9 
10 Because nums[0] + nums[1] = 2 + 7 = 9,
11 return [0, 1].
12 
13 
14 """
15 
16 
17 """
18 第一种是思路简单的方法,先遍历求出目标值,再遍历目标值是否再数组中,
19 判断如果下标相等则继续,最后返回[i,j]
20 """
21 class Solution1(object):
22     def twoSum(self, nums, target):
23         n = len(nums)
24         for i in range(n):
25             a = target - nums[i]
26             if (a in nums):       #这里其实隐含了一层循环
27                 j = nums.index(a)
28                 if (i==j):
29                     continue
30                 else:
31                     return [i,j]
32                     break
33             else:
34                 continue
35 """
36 第二种方法用了dict查找,提高效率
37 enumerate函数用法:
38 seasons = ['Spring', 'Summer', 'Fall']
39 list(enumerate(seasons))
40 [(0, 'Spring'), (1, 'Summer'), (2, 'Fall')]
41 """
42 class Solution2(object):
43     def twoSum(self, nums, target):
44         dict = {}
45         for i, num in enumerate(nums):
46             if target - num in dict:
47                 return [dict[target - num], i]
48             else:
49                 dict[num] = i
50 nums = [2, 7, 11, 15]
51 target = 9
52 result1 = Solution1()
53 result2 = Solution2()
54 print(result1.twoSum(nums, target))
55 print(result1.twoSum(nums, target))
原文地址:https://www.cnblogs.com/yawenw/p/12250459.html