Two Sum Solution in Python

Yixuan Zhou
2 min readAug 2, 2020

--

Today is the first day of my LeetCode journey, I’d like to share my solutions and record the trajectory of my own growth development.

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].

My Solution is using a dictionary:

In the above solution, the process looks like following:

target = 9

i = 0, num = 2, n = 7, h[2] = 0;

i = 1, num = 7, n = 2, since n=2 is in h as the key, return [h[2],1] = [0,1]

i = 2, num = 11, n = -2, h[11] = 2;

i = 3, num = 15, n = -6, h[15] = 3

Runtime is 44 ms, memory is 15.1 MB

Another solution using dictionary is based on item:

dict = {}
for i in nums:
if i in dict.keys():
if i == dict.get(i):
return [nums.index(i), nums.index(i, nums.index(i)+1)]
else:
# follow the queue number
return [nums.index(dict.get(i)), nums.index(i)]
else:
dict.update({target-i: i})

Runtime is 36 ms, memory is 14.2 MB

--

--

No responses yet