【哈希表】leetcode1——两数之和

编号1: 两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。数组

你能够假设每种输入只会对应一个答案。可是,数组中同一个元素不能使用两遍。code

示例:索引

给定 nums = [2, 7, 11, 15], target = 9
由于 nums[0] + nums[1] = 2 + 7 = 9
因此返回 [0, 1]

思路

暴力法即采用两层for循环,你们很容易写出来,这里咱们能够利用map操做,map中的key为nums数组中的数值,value为其对应的下标。get

具体代码以下:for循环

//哈希表中的key为nums中的值,val为值的索引下标
func twoSum(nums []int, target int) []int {
	mp := make(map[int]int)
	for i, num := range nums {
		another := target - num //与num和为target的另外一个数
		if anotherIndex, ok := mp[another]; ok {
			return []int{anotherIndex, i}
		}
		mp[num] = i
	}
	return []int{}
}