一、前言
两数之和是LeetCode中的第1道题,简单难度,Tags包含array与hash-table。
二、问题描述
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target 的那两个整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。你可以按任意顺序返回答案。
三、Solution
1、 暴力查找
func twoSum(nums []int, target int) []int {
len := len(nums)
for i := 0; i < len; i++ {
a := nums[i]
for j := i + 1; j < len; j++ {
b := nums[j]
if a+b == target {
return []int{i, j}
}
}
}
return nil
}
2、哈希表
暴力查找花费的时间主要在于找到target-v,因此我们可以使用map来存储v和i,这样就大大减少了查找target-v和j的时间。
func twoSum(nums []int, target int) []int {
maptable := map[int]int{}
for i, v := range nums {
if j, ok := maptable[target-v]; ok {
return []int{i, j}
} else {
maptable[v] = i
}
}
return nil
}
四、总结
这道题主要是考察使用哈希表来减少查找时间的技巧。