1. Two Sum
[Easy] “Given an array of integers, return indices of the two numbers such that they add up to a specific target."
Python3:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
elems = {}
for idx, num in enumerate(nums):
diff = target - num
if elems.get(num) is not None:
return [elems[num], idx]
# store complement index
elems[diff] = idx
Go:
func twoSum(nums []int, target int) []int {
candidates := make(map[int]int)
for i, num := range nums {
for candidate, index := range candidates {
// don't search for current candidate; check if solution
if (index != i) && (num == (target - candidate)) {
return []int{index, i}
}
}
// preserve index of candidate
candidates[num] = i
}
return []int{0, 0}
}