一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第3天,点击查看活动详情。
Go学习打卡Day03 map
-
Go语言中提供的映射关系容器为
map,其内部使用散列表(hash)实现。 -
map是一种无序的基于
key-value的数据结构,Go语言中的map是引用类型,必须初始化才能使用。 -
Go语言中
map的定义语法如下:- KeyType:表示键的类型。
- ValueType:表示键对应的值的类型。
map[KeyType]ValueType -
map类型的变量默认初始值为nil,需要使用make()函数来分配内存。语法为:
make(map[KeyType]ValueType, [cap])
1、基本使用
package main
import "fmt"
func main() {
info := make(map[string]int)
info["Coke"] = 18
info["Ice"] = 19
fmt.Println(info)
fmt.Println(info["Coke"])
fmt.Printf("type of a:%T\n", info)
user := map[string]int{
"coke": 18,
"Ice": 20,
}
fmt.Println(user)
}
// map[Coke:18 Ice:19]
// 18
// type of a:map[string]int
// map[Ice:20 coke:18]
判断key是否存在
value, ok := map[key]
Demo
package main
import "fmt"
func main() {
info := make(map[string]int)
info["Coke"] = 18
info["Ice"] = 19
info["wow"] = 20
if v, ok := info["Coke"]; ok {
fmt.Println(v)
} else {
fmt.Println("Not exist")
}
}
//18
map的遍历
package main
import "fmt"
func main() {
mp := make(map[string]int)
mp["A"] = 1
mp["B"] = 2
mp["D"] = 3
mp["C"] = 4
for k, v := range mp {
fmt.Println(k, v)
}
}
注意: 遍历map时的元素顺序与添加键值对的顺序无关。
按照指定顺序遍历map
package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano()) //seed
mp := make(map[string]int)
for i := 0; i < 10; i++ {
key := fmt.Sprintf("Coke%02d", i)
value := rand.Intn(100)
mp[key] = value
}
keys := make([]string, 0)
for k, _ := range mp {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Println(k, mp[k])
}
}
2、map引用,单词计数
package main
import (
"fmt"
"strings"
)
func main() {
str := "how are you welcome you are love is are ha ha you"
strs := strings.Split(str, " ")
fmt.Println(strs)
mp := make(map[string]int)
for _, k := range strs {
mp[k]++
}
fmt.Println(mp)
}
Go刷题 每日语法练习
1. 两数之和
func twoSum(nums []int, target int) []int {
mp := make(map[int]int)
for k, v := range nums {
if pos, ok := mp[target - v]; ok {
return []int {pos, k}
}
mp[v] = k
}
return nil
}
380. O(1) 时间插入、删除和获取随机元素
type RandomizedSet struct {
nums []int
mp map[int]int
}
func Constructor() RandomizedSet {
return RandomizedSet { []int{}, map[int]int{} }
}
func (this *RandomizedSet) Insert(val int) bool {
if _,ok := this.mp[val]; ok {
return false
}
this.mp[val] = len(this.nums)
this.nums = append(this.nums, val)
return true
}
func (this *RandomizedSet) Remove(val int) bool {
idx, ok := this.mp[val]
if !ok {
return false
}
las := len(this.nums) - 1
this.nums[idx] = this.nums[las]
this.mp[this.nums[idx]] = idx
this.nums = this.nums[:las]
delete(this.mp, val)
return true
}
func (this *RandomizedSet) GetRandom() int {
return this.nums[rand.Intn(len(this.nums))]
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* obj := Constructor();
* param_1 := obj.Insert(val);
* param_2 := obj.Remove(val);
* param_3 := obj.GetRandom();
*/