I read the guiding solution to twoSum in leetcodes ;
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Approach 3: One-pass Hash Table
It turns out we can do it in one-pass. While we iterate and inserting elements into the table, we also look back to check if current element's complement already exists in the table. If it exists, we have found a solution and return immediately.
and mimic a python solution
class Solution:
def twoSum(self, nums, target) -> List[int]:
"""
:type nums: List[int]
:type target: int
"""
nums_d = {}
for i in range(len(nums)):
complement = target - nums[i]
if nums_d.get(complement) != None: #Check None not True Value
return [i, nums_d.get(complement)]
nums_d[nums[i]] = i #produce a map
return []
Unfortunately, my solution is only faster than 81%, which I thought was a best solution.
Runtime: 40 ms, faster than 81.00% of Python3 online submissions for Two Sum. Memory Usage: 14.3 MB, less than 5.08% of Python3 online submissions for Two Sum. Next challenges:
How could continue to improve the code, and I am curious about the approaches of the top 20%.