Python solution


  • 2
    X
    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            hashTable = {}
            for i in range(len(nums)):
                hashTable[nums[i]] = i
            
            for i in range(len(nums)):
                if target - nums[i] in hashTable and i != hashTable[target - nums[i]]:
                    return [i, hashTable[target-nums[i]]]
            
            return []

  • 2
    N

    There are two things you can avoid here:

    1. Passing on the array more than once
    2. Checking if the number you found is not your current number (the right side of theand)
    class Solution(object):
        def twoSum(self, nums, target):
            h = {}
            for i, num in enumerate(nums):
                if (target - num) in h:
                    return [i, h[target - num]]
                h[num] = i
    

  • -1
    M
    This post is deleted!

  • 0
    N
    This post is deleted!

Log in to reply
 

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