Description

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


Ideas

map來紀錄訪問過的數值(key: number, value: index)。

在訪問數值時,目標值和當前數值的差即是另一個數值。若目標值和當前數值的差為map其中的一個key話即找到解。


Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
func twoSum(nums []int, target int) []int {
    _map := make(map[int]int)
    for i := 0; i < len(nums); i++ {
        if _, ok := _map[target - nums[i]]; ok {
            return []int {_map[target - nums[i]], i}
        } else {
            _map[nums[i]] = i
        }
    }
    return nil
}