Github上每日都更新,会将我从0开始在leetcode学习的算法题进行汇总上传,代码上会有点小注释,欢迎来看哈哈哈哈哈
https://github.com/kucfire/go-leetcode
由于平时工作还是太忙了,csdn这边不定时更新
001两数之和
package main
import (
"fmt"
)
func twoSum(nums
[]int, target
int) []int {
for i
:= 0; i
< len(nums
); i
++ {
for j
:= i
+ 1; j
< len(nums
); j
++ {
if nums
[i
]+nums
[j
] == target
{
return []int{i
, j
}
}
}
}
return nil
}
func twoSum2(nums
[]int, target
int) []int {
head
, tail
:= 0, len(nums
)-1
for head
< tail
{
if nums
[head
]+nums
[tail
] > target
{
tail
--
} else if nums
[head
]+nums
[tail
] < target
{
head
++
} else {
return []int{head
, tail
}
}
}
return nil
}
func twoSum3(nums
[]int, target
int) []int {
hashMap
:= make(map[int]int)
for i
, num
:= range nums
{
if v
, ok
:= hashMap
[num
]; ok
{
nums
[0] = v
nums
[1] = i
return nums
[:2]
}
hashMap
[target
-num
] = i
}
return nil
}
func main() {
example1
:= []int{2, 7, 11, 26}
example1Target
:= 9
fmt
.Println(twoSum(example1
, example1Target
))
fmt
.Println(twoSum2(example1
, example1Target
))
fmt
.Println(twoSum3(example1
, example1Target
))
}
该题可以使用两种方法进行解答(2020-10-05更新,本来是有三种方法可以解答的,但是leetcode更新例题之后,双指针法不能通过测试了)