Two Sum

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.

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

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

假定只有唯一解的情况下在数组中找出和为target的两个数

Solution

func twoSum(nums []int, target int) []int {
    res := make([]int, 2)
    m := map[int]int{}

    for i := range nums {
        m[target - nums[i]] = i
    }

    for i := range nums {
        idx, ok := m[nums[i]]
        if ok {
            if i == idx {
                continue
            }
            res[0] = idx
            res[1] = i
            sort.Ints(res)
            break
        }
        continue
    }

    return res
}

Similar Problem