V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
plantparknet
V2EX  ›  LeetCode

leetcode two-sum 的问题

  •  
  •   plantparknet · Jul 6, 2015 · 3723 views
    This topic created in 3954 days ago, the information mentioned may be changed or developed.

    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 replies    2015-07-07 09:27:44 +08:00
    msg7086
        1
    msg7086  
       Jul 6, 2015
    对于每个num里的数,找他对于target的差是不是也在sum里。
    plantparknet
        2
    plantparknet  
    OP
       Jul 6, 2015
    @msg7086 为何返回的是 (dict[target-x]+1, i+1) 呢?原文要求的是index1 和index2,两个数值大小与sum的长度没关系吧
    msg7086
        3
    msg7086  
       Jul 6, 2015   ❤️ 1
    dict[x]里存的就是index。
    yuankui
        4
    yuankui  
       Jul 7, 2015
    python不是直接可以a+b吗??
    yuankui
        5
    yuankui  
       Jul 7, 2015
    不好意思,看错题了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   998 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 17:59 · PVG 01:59 · LAX 10:59 · JFK 13:59
    ♥ Do have faith in what you're doing.