leetcode刷题:1、两数之和

leetcode刷题:1、两数之和_第1张图片

解题:

       使用语言:python

       解法一:

       

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(len(nums)):
                if j>i:                 
                    if target == nums[i] + nums[j]:
                        return list((i,j))

解法2:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashmap = {}
        for i,num in enumerate(nums):
            diff = target - num
            if diff in hashmap:
                return [hashmap[diff],i]
            hashmap[num] = i

       解法二引入字典,利用enumerate函数产生键值然后存储在字典里,将产生的值存为键,产生的键存为值,因为在字典里可以利用key in dict判断键是否在字典里,利用差值判断键是否存在,存在则输出相应的值(即输入列表的键)

你可能感兴趣的:(leetcode学习,leetcode)