leetcode two-sum 的问题

2015-07-06 23:33:30 +08:00
 plantparknet

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

class Solution:
    # @return a tuple, (index1, index2)
    def twoSum(self, num, target):
        dict = {}
        for i in range(len(num)):
            x = num[i]
            if target-x in dict:
                return (dict[target-x]+1, i+1)
            dict[x] = i

这段 twoSum 函数的逻辑是啥呢?

3132 次点击
所在节点    LeetCode
5 条回复
msg7086
2015-07-06 23:37:08 +08:00
对于每个num里的数,找他对于target的差是不是也在sum里。
plantparknet
2015-07-06 23:40:11 +08:00
@msg7086 为何返回的是 (dict[target-x]+1, i+1) 呢?原文要求的是index1 和index2,两个数值大小与sum的长度没关系吧
msg7086
2015-07-06 23:51:37 +08:00
dict[x]里存的就是index。
yuankui
2015-07-07 09:27:11 +08:00
python不是直接可以a+b吗??
yuankui
2015-07-07 09:27:44 +08:00
不好意思,看错题了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/203814

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX