Algo - Two Number Sum

Write a function which takes a non-empty array of distinct integers and a integer representing a target sum.

If the value of any two nums in the array sum up equal to the value of the target, the fuction should return the nums in an array.

Return an empty array if no two nums sum up to the target.

Go solution:

package main

func TwoSum(array []int, target int) []int {
    lookUp := map[int]int{}
    for _, it := range(array) {
        if val, ok := lookUp[it]; ok {
            return []int{it, val}
        } else {
            lookUp[target-it] = it
        }
    }
    return []int{}
}

Python solution:

def twoSum(array, targetSum):
    cache = {}
    for a in array:
        val = cache.get(a, None)
        if val is not None:
            return [a, val]
        cache[targetSum-a] = a
    return []

留言

熱門文章