V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
plantparknet
V2EX  ›  LeetCode

leetcode two-sum 的问题

  •  
  •   plantparknet · 2015-07-06 23:33:30 +08:00 · 3122 次点击
    这是一个创建于 3216 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 函数的逻辑是啥呢?

    5 条回复    2015-07-07 09:27:44 +08:00
    msg7086
        1
    msg7086  
       2015-07-06 23:37:08 +08:00
    对于每个num里的数,找他对于target的差是不是也在sum里。
    plantparknet
        2
    plantparknet  
    OP
       2015-07-06 23:40:11 +08:00
    @msg7086 为何返回的是 (dict[target-x]+1, i+1) 呢?原文要求的是index1 和index2,两个数值大小与sum的长度没关系吧
    msg7086
        3
    msg7086  
       2015-07-06 23:51:37 +08:00   ❤️ 1
    dict[x]里存的就是index。
    yuankui
        4
    yuankui  
       2015-07-07 09:27:11 +08:00
    python不是直接可以a+b吗??
    yuankui
        5
    yuankui  
       2015-07-07 09:27:44 +08:00
    不好意思,看错题了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5800 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 06:20 · PVG 14:20 · LAX 23:20 · JFK 02:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.