python-leetCode-给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的两个整数

本文详细解析了在整数数组中寻找两数之和等于目标值的算法,包括暴力解法、使用哈希表优化的解决方案以及遍历列表的简单方法。通过对比不同方法的时间复杂度,展示了如何有效提升算法效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的 两个 整数。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
  • 示例: 给定 nums = [2, 7, 11, 15],
    target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]

方法一:

暴力解法, 时间复杂度O(n^2)

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

方法二:

使用哈希表,通过以空间换取速度的方式,我们可以将查找时间从 O(n^2)降低到 O(n)。在python中列表字典的即为哈希类型。**

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

在这里插入图片描述
方法二比方法一快了十多倍,原因在于方法二使用了空间换时间的思路,可以将查找时间从 O(n^2)降低到 O(n)。在python中列表字典的即为哈希类型。

另一种写法
利用哈希字典查找,通过枚举将数值对应关系放入字典中,然后判断目标值和每一个值得差值在不在字典中。时间复杂度为O(n) 空间复杂度为O(n),相对容易理解一些

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
	    dict = {}
	    index_list = []
	    for i, m in enumerate(nums):
	        dict[m] = i
	    for i, m in enumerate(nums):
	        j = dict.get(target - m)
	        if j is not None:
	            index_list.append(i)
	            index_list.append(j)
	    return list(set(index_list))

方法三:

遍历列表,计算目标数与nums[i]的差,判断差是否在列表nums[i+1]里面即可,此法更加简单易懂

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        res = []
        # 遍历列表
        for i in range(len(nums)):
            # 计算需要找到的下一个目标数字
            ans = target-nums[i]
                # 在剩下的元素,查找是否存在该数字
            if ans in nums[i+1:]:
                # 若存在,返回答案。这里由于是两数之和,可采用.index()方法
                # 获得目标元素在nums[i+1:]这个子数组中的索引后,还需加上i+1才是该元素在nums中的索引
                res = [i, nums[i+1:].index(ans)+i+1]
                return res
        return res
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天下·第二

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值