5 map综合举例使用说明package main
import "fmt"
func main ( ) {
lmMap:= make ( map [ string ] string , 10 )
lmMap[ "sex" ] = "男"
lmMap[ "age" ] = "30"
lmMap[ "name" ] = "福小林"
fmt. Println ( lmMap)
fmt. Println ( lmMap[ "name" ] )
value, ok := lmMap[ "sex" ]
fmt. Println ( "lmMap中是否存在sex为key的值" , ok)
fmt. Println ( "lmMap[\"sex\"]=" + value)
scoreMap := make ( map [ string ] int )
scoreMap[ "张三" ] = 88
scoreMap[ "李四" ] = 95
scoreMap[ "王五" ] = 57
for k, v := range scoreMap {
fmt. Println ( k, v)
}
delete ( scoreMap, "张三" )
fmt. Println ( scoreMap)
var s1= make ( [ ] map [ int ] string , 10 , 10 )
s1[ 0 ] = make ( map [ int ] string , 3 )
s1[ 1 ] = make ( map [ int ] string , 3 )
s1[ 0 ] [ 10 ] = "第一个"
s1[ 1 ] [ 22 ] = "two"
fmt. Println ( s1[ 0 ] )
fmt. Println ( s1)
}
复制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
6 map练习题 转载力扣LeetCode
https://leetcode-cn.com/problems/two-sum
两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [ 2 , 7 , 11 , 15 ] , target = 9
因为 nums[ 0 ] + nums[ 1 ] = 2 + 7 = 9
所以返回 [ 0 , 1 ]
复制
1 2 3 4
解答 package main
import "fmt"
func main ( ) {
nums := [ ] int { - 1 , 5 , - 2 , - 3 , - 4 , - 5 }
arr := twoSum ( nums, 0 )
fmt. Println ( arr)
}
func twoSum ( nums [ ] int , target int ) [ ] int {
hashTable := map [ int ] int { }
for i, x := range nums {
if p, ok := hashTable[ target- x] ; ok {
return [ ] int { p, i}
}
hashTable[ x] = i
}
return nil
}
复制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
7 map总结 map必须借助make分配内存空间,否则是nil 字面量初始化必修保证key是唯一的,否则error map传递的是引用,就是说形参会改变实参的值 直接对map对象使用[]操作符获得的对象不能直接修改状态 map中存储指针而不是结构体