Posted on Jul 10 • Edited on Jul 14
Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Python
####Double Loops (Runtime: 2441ms, Memory: 13.4MB)
#DECLARE nums: ARRAY of INTEGER
#DECLARE target: INTEGER
class Solution:
def twoSum(self, nums, target):
length = len(nums)
for i in range(length-1):
for j in range((i+1), length):
if nums[i] + nums[j] == target:
return i, j
return None
####Hashing Algorithm (Runtime: 0ms, Memory: 12.8MB)
#DECLARE nums: ARRAY of INTEGER
#DECLARE target: INTEGER
class Solution:
def twoSum(self, nums, target):
seen_map = {}
for i, value in enumerate(nums):
if (target-value) in seen_map:
return seen_map[target-value], i
seen_map[value] = i
return None
Enter fullscreen mode Exit fullscreen mode
Thoughts
I think the most important thing that the Two Sum question teaches is how to use Dictionaries effectively. It helps you understand that using Direct Access is much faster than looping through all the elements. Personally, it made me step back and think more about improving performance rather than simply solving the problem.
답글 남기기