add leedcode ex.1

master
ZGGSONG 3 years ago
parent 03fa1d4854
commit e38ee114cb

@ -0,0 +1,48 @@
package main
import "fmt"
/**
1.
nums target target
nums = [2,7,11,15], target = 9
[0,1]
nums[0] + nums[1] == 9 [0, 1]
*/
func main() {
array := []int{2, 7, 11, 15}
target := 9
res := twoSum2(array, target)
fmt.Println(res)
}
//暴力方法
func twoSum(nums []int, target int) []int {
for i := 0; i < len(nums)-1; i++ {
for j := i + 1; j < len(nums); j++ {
if nums[i]+nums[j] == target {
return []int{i, j}
}
}
}
return nil
}
//哈希表法
//slice [ 1, 3, 4, 6]
//slice index 0 1 2 3
//map key 3, 1, 6, 4
//map value 1, 0, 3, 2
func twoSum2(nums []int, target int) []int {
tmp := make(map[int]int)
for k, v := range nums {
if value, ok := tmp[target-v]; ok {
return []int{value, k}
} else {
tmp[v] = k
}
}
return nil
}

@ -9,7 +9,7 @@ import (
func main() { func main() {
myMap := make(map[string]int) myMap := make(map[string]int)
myMap["song"] = 1 myMap["song"] = 1
myMap["zong"] = 2 myMap["zhang"] = 2
fmt.Println(myMap) fmt.Println(myMap)
myMap2 := map[string]string{ myMap2 := map[string]string{
@ -38,7 +38,7 @@ func main() {
// IsExist 键是否存在 // IsExist 键是否存在
func IsExist() (int, bool) { func IsExist() (int, bool) {
fmt.Println("===IsExist===") fmt.Println("===IsExist===")
mMap := make(map[string]int) mMap := make(map[string]int) //map类型的变量默认初始值为nil需要使用make()函数来分配内存
mMap["张三"] = 333 mMap["张三"] = 333
mMap["李四"] = 444 mMap["李四"] = 444
v, ok := mMap["张三"] v, ok := mMap["张三"]
@ -111,10 +111,6 @@ func RangeMap2() {
fmt.Println() fmt.Println()
} }
func test() {
SliceMap()
}
// MapSlice 元素为map类型的切片 // MapSlice 元素为map类型的切片
func MapSlice() { func MapSlice() {
fmt.Println("===元素为map类型的切片===") fmt.Println("===元素为map类型的切片===")

@ -6,9 +6,9 @@ import (
) )
func main() { func main() {
var a []string var a []string //声明一个字符串切片
b := []int{} b := []int{} //声明一个整型切片并初始化
c := []bool{true, false} c := []bool{true, false} //声明一个整型切片并初始化
fmt.Println(a) fmt.Println(a)
fmt.Println(b) fmt.Println(b)
fmt.Println(c) fmt.Println(c)
@ -76,6 +76,6 @@ func main() {
sort.Slice(ms, func(i, j int) bool { sort.Slice(ms, func(i, j int) bool {
return ms[i] < ms[j] return ms[i] < ms[j]
}) })
fmt.Printf("Sort: %v\n%v\n", mm, ms) fmt.Printf("Sort: %v\n%v\n", mm, ms)
} }

Loading…
Cancel
Save