leecode 两数之和的四种方法

leecode 两数之和的四种解法:

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
解法1:

class Solution:
    def twoSum( sself,nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        i=0
        j=1
        for num1 in nums:
         i=i+1
         j=i
         for num2 in nums[j:]:
            j=j+1
            if num1+num2==target:
                return [i-1,j-1]

这种方法最容易想到,两个for循环就可及解决,但是时间复杂度太高,leecode没给过

解法2:

class Solution:
    def twoSum(self,nums,target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        j=-1
        lens=len(nums)
        print(range(lens))
        for n1 in range(lens):
            t=nums[:n1]
            if target-nums[n1] in t:
                j=t.index(target-nums[n1])
                break
        return [j,n1]

但是时间太长,内存占用也比较大
但是时间长,内存占用多

解法3:
这里利用了字典来查找,速度提升很大,与哈希表的原理有关

class Solution:
    def twoSum(self,nums,target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict1 = {}
        for i, num in enumerate(nums):
            dict1[num] = i  # 调换一个顺序
        for i, num in enumerate(nums):
            j=dict1.get(target-num)
            if j!=None and i!=j :
                return [i,j]

关于enumerate函数
效果如下:

在这里插入图片描述
解法4:

class Solution:
    def twoSum(self,nums,target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict1 = {}
        for i, num in enumerate(nums):
            j=dict1.get(target-num)
            if j!=None and j!=i:
                return[j,i]
            dict1[num] = i  # 调换一个顺序。在后面防止字典键值有重复

这个就只用到了一个循环
但效果、、、
在这里插入图片描述

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值