leetcode 001 Two Sum (两数之和) python3 两种思路(遍历数组两次/一次)

所有Leetcode题目不定期汇总在 Github, 欢迎大家批评指正,讨论交流。
class Solution:
    def twoSum(self, nums: 'List[int]', target: 'int') -> 'List[int]':


        # Approach one 低效
#         dic = {}
#         length = len(nums)
#         for i in range(length):
#             dic[nums[i]] = i

#         for i in range(length):     # 考虑一个target由两个相同的数字组成。例如[3,3] 6
#             res =  target - nums[i]
#             if res in dic.keys() and dic.get(res) != i:
#                 return [i, dic.get(res)]


        # Approach two
        # dic = {}
        # for i,n in enumerate(nums):
        #     m = target - n
        #     if n not in dic.keys():
        #         dic[m] = i
        #     else:
        #         return [dic.get(n),i]


        # Approach three  细节优化
        hashed = {}
        for i,n in enumerate(nums):
            if n in hashed: return  [hashed[n],i]
            hashed[target-n] = i
           
所有Leetcode题目不定期汇总在 Github, 欢迎大家批评指正,讨论交流。

你可能感兴趣的:(【leetcode】,刷题总结,&,编程心得)