Python Hashtable Solution

  • 0

    Build a hashtable and look for the two numbers in one iteration.

    class Solution(object):
        def twoSum(self, nums, target):
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            hashtable = {}
            for index, num in enumerate(nums):
                if (target - num) in hashtable:
                    return [hashtable[(target - num)], index]
                hashtable[num] = index
            return [] # not found

    P.S. hashtable gets overwritten when duplicates exist

Log in to reply

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