LeetCode 1


### 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.

  • 题意:
    输入一个数组和一个target,该数组中恰好有两个数和为target(数组中每个数只能使用一次),返回这两个数的下标

  • 思路:
    用字典解决, 将数组的值作为字典的key, 将数组的下标作为字典的value, 具体看代码



Example:


  1. Given nums = [2, 7, 11, 15], target = 9,
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].


代码


Golang

func twoSum(nums []int, target int) []int {
	num_map := make(map[int]int)
	for i, v := range nums {
		var ok bool
		var j int
		j, ok = num_map[target-v]
		if ok {
            return []int{j, i}
		} else {
            num_map[v] = i
		}
	}
	return nil
}

posted @ 2018-03-12 10:59  shengwudiyi  阅读(90)  评论(0编辑  收藏  举报