1. Two Sum [easy] (Python)

这篇博客介绍了LeetCode中的1. Two Sum问题的解决方案。提供了两种方法,包括暴力求解和利用哈希(字典)的方法。通过示例解释了如何在给定数组中找到两个数,使它们的和为目标值,并返回其数组下标。

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

题目链接

https://leetcode-cn.com/problems/two-sum

题目原文

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

English
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

思路方法

方法一:暴力解决

直接进行两次循环,遍历所有配对,直到找到合适的一对

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        l = len(nums)
        for i in range(l-1):
            for j in range(i+1,l):
                if nums[i]+nums[j] == target:
                    return [i,j]        

方法二:利用哈希(字典)

创建一个字典,把nums中的每个数字依次加入字典中,同时查询target-nums[i]是否在字典里,在的话就提取index。
这里不需要考虑nums中有重复数字的问题。因为如果target等于两重复数字之和,那么在第二个重复数字进入字典之前,就已经return了,如果target不等于重复数字之和,第二个重复数字进入字典时,会覆盖第一个重复数字的index,不影响结果。

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        n = len(nums)
        lookup = {}
        for i in range(n):
            tmp = target - nums[i]
            if tmp in lookup:
                return [lookup[tmp], i]
            lookup[nums[i]] = i

第一次写优快云,开心开心!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值