feat: 两数之和go实现
This commit is contained in:
parent
790d84ddda
commit
6701af4f89
30
go_solutions/leetcode-go/array/easy_two_sum.go
Normal file
30
go_solutions/leetcode-go/array/easy_two_sum.go
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
/*
|
||||||
|
使用哈希表
|
||||||
|
*/
|
||||||
|
func twoSum(nums []int, target int) []int {
|
||||||
|
hashTable := map[int]int{}
|
||||||
|
for i, x := range nums {
|
||||||
|
if val, ok := hashTable[target-x]; ok {
|
||||||
|
return []int{val, i}
|
||||||
|
}
|
||||||
|
hashTable[x] = i
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
暴力枚举,首先遍历整个数组,之后再遍历后边的所有元素,如果两个元素相加的值为target,就返回这两个
|
||||||
|
下标
|
||||||
|
*/
|
||||||
|
func f1(nums []int, target int) []int {
|
||||||
|
for i, x := range nums {
|
||||||
|
for j := i + 1; j < len(nums); j++ {
|
||||||
|
if x+nums[j] == target {
|
||||||
|
return []int{i, j}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user