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 FOR Loops (Runtime: 2100ms, Memory: 13.3MB)
#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.9MB)
#DECLARE nums: ARRAY of INTEGER
#DECLARE target: INTEGER
class Solution:
def twoSum(self, nums, target):
Seen = {}
for i, Value in enumerate(nums):
if (target - Value) in Seen:
return Seen[target - Value], i
Seen[Value] = i
return None
Top comments (0)