Two Sum
description easy
accepted(one bang)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in nums:
we_want = target - i
temp = nums[nums.index(i)+1:]
if we_want in temp:
index = temp.index(we_want) + nums.index(i)+1
return [nums.index(i), index]
faster solution using hashmap:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
map = {}
for i,n in enumerate(nums):
diff = target - n
if diff in map:
return(map[diff], i)
map[n] = i
return
like what this image protrayed, we keep a record of value:index in a hashmap. we iterate through the array, and once we find the second value, we are garrenteed to find the solution to the problem.