LeetCode-1.Two Sum

本文深入探讨了经典的两数之和算法问题,利用字典数据结构实现高效查找,避免重复元素使用,确保唯一解的存在。文章详细解释了字典在算法中的应用,包括键值对的设置和查找过程,通过实例演示了算法的具体实现。

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

Description:

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].

考察的点:
1.映射关系:映射关系有列表list 和字典dict,列表通过编号(按顺序)访问各个值,字典通过名称(不按顺序)访问其值。
2.基本的字典操作:
d[k]=v 将值v关联到键k
k in d 检查字典d是否包含键为k的项。
3.难点:
表达式 k in d(其中d是一个字典)查找的是键而不是值!!!

class Solution:
    def twoSum(self, nums, target):
        seen={} #empty dict
        for i,n in enumerate(nums):  
            other=target-n 
            
            if other in seen: #'other' is a key,not a value
                return[seen[other],i]  #seen[other] returns a value,actually a index
            else:
                seen[n]=i  #将没用的放入到字典中,到了真有用的才能正确计数,否则seen[other]返回的是0,
            print(seen)
            print("*"*10)
                
nums=[2,7,11,15]
target=26
t=Solution()
t.twoSum(nums,target)
class Solution:
    def twoSum(self, nums, target):
        dict={}
        for i in range(len(nums)):
            print(i)
            if target-nums[i] not in dict:
                dict[nums[i]]=i  #nums[i] is a key ,i is a value
            else:
                return [dict[target-nums[i]],i] #now dict[target-nums[i]] 是倒数第二个,i is the last one.
            print(dict)
            
            print("*"*10)

nums=[2,7,11,15]
target=26
t=Solution()
t.twoSum(nums,target)
                

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值