Python solution using hash


  • 34
    G
    class Solution:
        # @return a tuple, (index1, index2)
        # 8:42
        def twoSum(self, num, target):
            map = {}
            for i in range(len(num)):
                if num[i] not in map:
                    map[target - num[i]] = i + 1
                else:
                    return map[num[i]], i + 1
    
            return -1, -1

  • 0
    C

    Haha, @Google, there's a miss " + 1" in the tenth line.
    It should be: return map[num[i]] + 1, i + 1
    Anyway, this is a terse Python code. Awesome.


  • 2
    G

    The +1 is being handled in the if branch already :)

    if num[i] not in map:
        map[target - num[i]] = i + 1
    else:
        return map[num[i]], i + 1
    

    You can also do:

    if num[i] not in map:
        map[target - num[i]] = i
    else:
        return map[num[i]] + 1, i + 1

  • 0
    I

    really different thinking. Thanks for sharing.


  • 15
    P

    simpler:

    def twoSum(self, nums, target):
            d={}
            for i,num in enumerate(nums):
                if target-num in d:
                    return d[target-num]+1, i+1
                d[num]=i

  • 0
    I
    This post is deleted!

  • 0
    Y

    @patrick40 this one is easier to understand, save all index of number in a dict for later search through.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.