LeetCode 第一题:两数之和 【1/1000 python】

 👤作者介绍:10年大厂数据\经营分析经验,现任大厂数据部门负责人。

会一些的技术:数据分析、算法、SQL、大数据相关、python

作者专栏每日更新:LeetCode解锁1000题: 打怪升级之旅https://blog.csdn.net/cciehl/category_12625714.html


python数据分析可视化:企业实战案例https://blog.csdn.net/cciehl/category_12615648.html

备注说明:方便大家阅读,统一使用python,带必要注释,公众号 数据分析螺丝钉 一起打怪升级

题目描述

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

暴力破解

其基本思想是遍历数组的每个元素 x,并查找是否存在一个值与 x 相加之和等于目标值 target。这种方法需要两层循环:外层循环遍历每个元素,内层循环查找是否存在符合条件的另一个元素

from typing import List

def twoSum(nums: List[int], target: int) -> List[int]:
    """
    Find two numbers such that they add up to a specific target number.

    Args:
    nums (List[int]): List of integers.
    target (int): The target sum.

    Returns:
    List[int]: Indices of the two numbers adding up to target, if any.
    """
    # 外层循环
    for i in range(len(nums)):
        # 内层循环,查找配对
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i, j]
    return []

def main():
    """
    Main function to test the twoSum function.
    """
    nums = [2, 7, 11, 15]
    target = 9
    result = twoSum(nums, target)
    print(f"Indices of the two numbers: {result}")

if __name__ == '__main__':
    main()

哈希表

一种直观的方法是使用两层循环,对每对可能的数字进行求和并比较是否等于目标值。但这种方法的时间复杂度较高,为O(n^2)。

一个更高效的方法是使用哈希表来减少查找时间。这种方法的基本思想是,遍历数组,对于每个元素,我们可以计算出其配对的数字(即 target - 当前数字),然后在哈希表中查找是否存在这样一个配对数字。如果存在,则直接返回当前数字和配对数字的下标。在遍历的过程中,将每个元素的值和它的索引添加到哈希表中,这样在查找配对数字时就可以快速进行。代码在练习的时候建议都加上注释方便阅读也更规范。

def twoSum(nums, target):
    """
    Finds two numbers such that they add up to a specific target number.

    :param nums: List of integers.
    :param target: Integer, the target sum.
    :return: A list containing the indices of the two numbers that add up to the target.
    """
    hashmap = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in hashmap:
            return [hashmap[complement], i]
        hashmap[num] = i
    return []

def main():
    """
    Main function to demonstrate the usage of twoSum function.
    """
    nums = [2,7,11,15]
    target = 9
    result = twoSum(nums, target)
    print(f"Indices of the two numbers that add up to {target}: {result}")

if __name__ == '__main__':
    main()

输出

f080bdbb20ea464ab56ad0ff9f2591aa.png

解释

  • 初始化一个空字典(哈希表)hashmap
  • 遍历数组 nums,其中 i 是当前数字的索引,num 是当前数字的值。
  • 计算 complement,即目标值 target 减去当前数字 num
  • 如果 complementhashmap 中,意味着我们找到了一个解,返回 [hashmap[complement], i],这里 hashmap[complement] 是配对数字的索引,i 是当前数字的索引。
  • 如果当前遍历的数字不是解的一部分,将其添加到 hashmap 中,键为数字的值,值为它的索引。
  • 如果遍历完整个数组都没有找到解,返回一个空列表。

这种方法的时间复杂度为O(n),因为我们只需要遍历一次数组,查找时间为O(1)。

劣势

空间开销:哈希表的主要劣势之一是它需要额外的空间来存储数据结构。对于大型数据集,这可能会成为问题,尤其是在内存资源受限的情况下。

 

 

  • 27
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[i] + nums[j] == target: return [i, j] ### 回答2: leetcode 第1是"两数之和",目要求在给定的整数数组中找到两个数,使它们的和等于一个目标值,并返回这两个数的索引。下面是使用哈希表解决这个问Python代码: ```python def twoSum(nums, target): # 创建一个空的哈希表 hashmap = {} # 遍历整个数组 for i, num in enumerate(nums): # 计算当前数字与目标值的差值 complement = target - num # 如果差值存在于哈希表中,则返回差值的索引和当前数字的索引 if complement in hashmap: return [hashmap[complement], i] # 将当前数字添加到哈希表中,索引作为键,数字作为值 hashmap[num] = i # 如果未找到符合条件的数字,则返回空列表 return [] ``` 这个算法的基本思想是,在遍历整个数组的过程中,先计算当前数字与目标值的差值,然后将差值与当前数字的索引存储在哈希表中。接下来,在遍历数组的过程中,如果差值存在于哈希表中,则说明找到了两个数的和等于目标值,直接返回这两个数的索引。如果遍历完成后仍未找到符合条件的数对,则返回空列表。这个算法的时间复杂度为 O(n),其中 n 为数组的长度。 ### 回答3: 目描述:两数之和 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回它们的数组下标。 示例: 输入:nums = [2,7,11,15], target = 9 输出:[0,1] 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。 思路:使用字典存储数组中的数字及其对应的下标,然后遍历数组找到与目标值的差值,如果差值也在字典中,说明找到了答案。 具体实现如下: ```python def twoSum(nums, target): # 创建一个字典存储数组中的数字及其对应的下标 num_dict = {} for i in range(len(nums)): # 计算与目标值的差值 complement = target - nums[i] # 如果差值也在字典中,说明找到了答案 if complement in num_dict: return [num_dict[complement], i] # 将数字及其对应的下标存入字典中 num_dict[nums[i]] = i return [] nums = [2, 7, 11, 15] target = 9 result = twoSum(nums, target) print(result) # 输出 [0, 1] ``` 以上就是 LeetCode 第1Python代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

数据分析螺丝钉

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

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

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

打赏作者

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

抵扣说明:

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

余额充值