plantparknet
V2EX  ›  LeetCode

leetcode two-sum 的问题

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