【哈希表】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{}
}
相關文章
相關標籤/搜索