为了账号安全,请及时绑定邮箱和手机立即绑定

向 Python 字典添加重复键(“Two Sum”问题)

向 Python 字典添加重复键(“Two Sum”问题)

jeck猫 2021-06-14 16:33:08
我一直在尝试向我的 python 字典(表)添加重复键以解决“二和”问题。给定一个整数数组,返回两个数字的索引,使它们相加为特定目标。我现在意识到这是不可能做到的,并且会很感激关于如何在没有蛮力的情况下解决这个问题的任何想法或建议。请记住,我这周开始尝试学习 Python。所以我很抱歉有一个简单的解决方案numbers = [0, 0, 0, 0, 0, 0, 0]  # initial listtarget = 6  # The sum of two numbers within list# Make list into dictionary where the given values are used as keys and actual values are indicestable = {valueKey: index for index, valueKey in enumerate(numbers)}print(table)>>> {0: 6}
查看完整描述

3 回答

?
白衣染霜花

TA贡献1796条经验 获得超10个赞

我不明白为什么你需要一个字典,除非你有多个目标。我会用 aset代替。


numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

target = 9

answer = set()

for i, iNumber in enumerate(numbers):

    for j, jNumber in enumerate(numbers):

        if i == j:

            continue

        mySum = iNumber + jNumber

        if (mySum == target):

            answer.add((i,j))


查看完整回答
反对 回复 2021-06-22
?
HUH函数

TA贡献1836条经验 获得超4个赞

我会对数组进行排序,进行某种二进制搜索来搜索目标的索引(或直接次要索引),并在较小的索引和使用二进制搜索找到的索引之间的索引中查找“二和”。

例如:数组 = [5,1,8,13,2,4,10,22] 目标 = 6

sorted_array = [1,2,4,5,8,10,13,22] binary_search_index = 4(数字 5)

所以知道你将你的数组减少到:[1,2,4,5],你可以在那里查看“两个总和”,可能使用 de min 和 max 索引。


查看完整回答
反对 回复 2021-06-22
  • 3 回答
  • 0 关注
  • 88 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号