纯记录,鼓励自己坚持下去。
题目1:
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案
func twoSum(nums []int, target int) []int {
1.双重遍历
var result []int
for i := 0; i < len(nums);i++{
for j := i+1;j<len(nums);j++{
if nums[i]+nums[j]==target{
result = append(result,i)
result = append(result,j)
}
}
}
return result
}
以上的时间复杂度因为遍历了两次所以较高,可以通过将数组存储进哈希表中,再遍历的话复杂度会变为n
func twoSum(nums []int, target int) []int {
//2.单次遍历
maparray := make(map[int]int) //执行用时为4ms
// maparray := map[int]int{} 执行用时为8ms
for i, a := range nums{
b := target - a
if j, ok := maparray[b]; ok{
return []int{i,j}
}
maparray[a] = i
}
return nil
}
这里出现一点让我疑惑的是,我本来是直接用map引用类型声明的,但我发现结果显示用make方法会缩短一倍运行时间,但不懂原因,礼貌求解!