Leetcode 1: Two Sum (my hashmap solution)

Python Solution:


class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # two pointers, apply to sorted array, O(nlogn) for sorting, O(n) for sorted array
        # hash map, O(n)
        
        #nums = [2,11,7,15], target = 9
        #hashmap={2:0,11:1,}
        
        hashmap = {} #python dictionary: store key:value pairs
        for i in range(len(nums)):
            #i=0, nums[0]=2, complement = 9 - 2 = 7
            #i=1, nums[1]=11, complement = 9 - 11 = -2, hashmap[11] = 1
            #i=2, nums[2]=7, complement = 9 - 7 = 2, find 2 in the keys of the hashmap
            complement = target- nums[i]
            if complement in hashmap:
                return [i, hashmap[complement]] #python list [2,0]
            hashmap[nums[i]] = i

 

Time Complexity: O(n)

Space Complexity: O(1)


Feeling tired? You can also try our free online no-installation required casual games: Here Please consider to follow my youtube channel to support me: