golang中set数据结构的使用示例
作者:Pecto 时间:2024-02-17 22:06:19
借助map实现
golang中没有set数据结构,一般是通过map实现,因为map的key值是不能重复的
示例
type empty struct {
}
// golang中的set数据类型
func MakeGolangSet(){
// 首先,空结构体内存消耗为0,其它数据结构如布尔值等均存在内存消耗
var e empty
fmt.Printf("empty struct memory is %v\n", unsafe.Sizeof(e))
fmt.Printf("bool memory is %v\n", unsafe.Sizeof(false))
set := make(map[string]struct{})
// ADD
set["foo"] = e
// DELETE
delete(set, "foo")
// set的规模
size := len(set)
fmt.Printf("set size is %v\n", size)
// 判断是否存在
set["foo"] = e
value, exist := set["foo"]
fmt.Printf("value is %v\n, exist is %v\n", value, exist)
}
算法应用
找两个数组的交集
// 两个数组的交集
func SectionWithTwoArray(num1, num2 []int) []int{
set := make(map[int]struct{}, 0)
var res []int
for _, v := range num1 {
if _, ok := set[v]; !ok {
// 去重
set[v] = struct{}{}
}
}
for _, v := range num2 {
if _, ok := set[v]; ok {
res = append(res, v)
// 将此v删掉,避免结果中出现重复数据
delete(set, v)
}
}
return res
}
来源:https://blog.csdn.net/weixin_41198062/article/details/124274991
标签:golang,set数据结构
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python os模块介绍
2021-11-06 20:53:16
![](https://img.aspxhome.com/file/2023/5/133325_0s.png)
Python range与enumerate函数区别解析
2022-03-05 21:40:20
自己写的一个PJBlog中可以双击输入验证码的修改
2009-05-17 10:51:00
PyTorch加载自己的数据集实例详解
2022-07-29 14:10:36
SQL查询效率-100w数据查询只要1秒
2008-08-20 18:25:00
python中模块导入模式详解
2022-04-03 08:54:29
![](https://img.aspxhome.com/file/2023/4/109474_0s.png)
python中几个常用函数的正确用法-lambda/filter/map/reduce
2022-02-17 14:52:45
对Python 数组的切片操作详解
2022-06-09 23:29:39
比较不错的函数式JavaScript编程指南教程
2023-08-25 08:24:41
Server.HTMLEncode让代码在页面里显示为源代码
2023-11-24 13:40:28
Laravel使用PHPQRCODE实现生成带有LOGO的二维码图片功能示例
2024-05-03 15:28:12
Python随机数用法实例详解【基于random模块】
2023-10-26 08:48:49
基于Python实现图像的傅里叶变换
2023-12-14 09:10:34
![](https://img.aspxhome.com/file/2023/3/90913_0s.jpg)
怎样修改 MySQL数据库中的密码
2008-11-27 15:35:00
Python3实现的爬虫爬取数据并存入mysql数据库操作示例
2022-11-06 15:18:59
![](https://img.aspxhome.com/file/2023/1/66351_0s.png)
SqlServer 执行计划及Sql查询优化初探
2024-01-14 23:03:01
![](https://img.aspxhome.com/file/2023/2/89692_1s.gif)
python scipy.spatial.distance 距离计算函数
2023-01-25 08:55:23
详解MySQL数据类型之数字类型正确使用
2010-06-20 15:02:00
可插入图片的TEXT文本框
2024-02-25 20:07:36
![](https://img.aspxhome.com/file/2023/4/56364_0s.png)
linux下如何备份还原mysql数据库
2010-08-08 08:59:00