Golang算法 - Leetcode

 主页   资讯   文章   代码   电子书 

1. Two Sum

Leetcode 链接

题目

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,每个数不能重复使用。数组中只可能存在一对数满足要求。要求给出满足要求的两个数的下标。

解决方案

用 map 就可以简单解决问题。

Go 代码

func twoSum(nums []int, target int) []int {
    res :=  []int{}

    mm := make(map[int]int)
    for i, v := range nums{
        index, ok := mm[target - v]
        if ok {
            res = []int{index, i}
            return res
        }
        mm[v] = i
    }
    return res 
}