首页 > 其他分享 >Leetcode 1.两数之和(hash)

Leetcode 1.两数之和(hash)

时间:2023-03-13 11:45:24浏览次数:43  
标签:__ hash target nums self return Leetcode 两数

题目链接在这里: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, nums, target)
25     print(ans)

 

标签:__,hash,target,nums,self,return,Leetcode,两数
From: https://www.cnblogs.com/keximeiruguo/p/17210781.html

相关文章