题目链接在这里:1. 两数之和 - 力扣(LeetCode)
这道题主要学习了python中哈希表的使用,类似于c++中的map容器
1 # 暴力
2 # class Solution:
3 # def twoSum(self, nums, target):
4 # n = len(nums)
5 # for i in range(n):
6 # for j in range(i+1,n):
7 # if nums[i]+nums[j]==target:
8 # return [i,j]
9 # return []
10
11 class Solution:
12 def twoSum(self, nums, target):
13 hash = dict()
14 for i,j in enumerate(nums):
15 if target - j in hash:
16 return [i, hash[target - j]]
17 hash[j] = i
18 return []
19
20 if __name__=="__main__":
21 nums = [3, 2, 4]
22 target = 6
23 self = 0
24 ans = Solution.twoSum(self=0, nums=nums, target=target)
25 print(ans)
标签:__,hash,target,nums,self,return,Leetcode,两数 From: https://blog.51cto.com/u_15793969/6132722