翻译自 Sparse Set - GeeksforGeeks

如果有大量的查询,如何有效地进行以下操作

  1. 插入
  2. 删减
  3. 搜索
  4. 清理/删除所有元素

一种解决方案是使用自平衡二进制搜索树,如红黑树、AVL树等。这种解决方案的插入、删除和搜索的时间复杂度为O(Log n)。

我们也可以使用哈希法。在散列法中,前三个操作的时间复杂度是O(1)。但第四个操作的时间复杂度是O(n)。

我们也可以使用 bit-vector (或直接访问表),但 bit-vector 也需要O(n)时间进行清除。

稀疏集的性能优于所有的BST、哈希和位向量。我们假设给定数据范围(或一个元素的最大值)和可以存储在集合中的最大元素数。我们的想法是维护两个数组:sparse[]和 dense[]。

dense[]   ==> 储存实际的元素
sparse[]  ==> 这就像我们使用元素作为索引的位向量。这里的值不是二进制的,而是密集数组的索引
maxVal    ==> 这个集合可以存储的最大值。sparse[]的大小等于maxVal + 1
capacity  ==> 集的容量。sparse的大小等于capacity。
n         ==> 当前Set中元素的数量
/* A C program to implement Sparse Set and its operations */
#include <algorithm>
#include <iostream>using namespace std;// A structure to hold the three parameters required to
// represent a sparse set.
class SSet
{int *sparse;   // To store indexes of actual elementsint *dense;       // To store actual set elementsint n;           // Current number of elementsint capacity;  // Capacity of set or size of dense[]int maxValue;  // Maximum value in set or size of sparse[]public:// ConstructorSSet(int maxV, int cap){sparse = new int[maxV + 1];dense = new int[cap];capacity = cap;maxValue = maxV;n = 0;     // No elements initially}// Destructor~SSet(){delete[] sparse;delete[] dense;}// If element is present, returns index of// element in dense[]. Else returns -1.int search(int x);// Inserts a new element into setvoid insert(int x);// Deletes an elementvoid deletion(int x);// Prints contents of setvoid print();// Removes all elements from setvoid clear() { n = 0; }// Finds intersection of this set with s// and returns pointer to result.SSet* intersection(SSet &s);// A function to find union of two sets// Time Complexity-O(n1+n2)SSet *setUnion(SSet &s);
};// If x is present in set, then returns index
// of it in dense[], else returns -1.
int SSet::search(int x)
{// Searched element must be in rangeif (x > maxValue)return -1;// The first condition verifies that 'x' is within 'n' in this set and the second// condition tells us that it is present in the data structure.if (sparse[x] < n && dense[sparse[x]] == x)return (sparse[x]);// Not foundreturn -1;
}// Inserts a new element into set
void SSet::insert(int x)
{// Corner cases, x must not be out of// range, dense[] should not be full and// x should not already be presentif (x > maxValue)return;if (n >= capacity)return;if (search(x) != -1)return;// Inserting into array-dense[] at index 'n'.dense[n] = x;// Mapping it to sparse[] array.sparse[x] = n;// Increment count of elements in setn++;
}// A function that deletes 'x' if present in this data
// structure, else it does nothing (just returns).
// By deleting 'x', we unset 'x' from this set.
void SSet::deletion(int x)
{// If x is not presentif (search(x) == -1)return;int temp = dense[n-1]; // Take an element from enddense[sparse[x]] = temp; // Overwrite.sparse[temp] = sparse[x]; // Overwrite.// Since one element has been deleted, we// decrement 'n' by 1.n--;
}// prints contents of set which are also content
// of dense[]
void SSet::print()
{for (int i=0; i<n; i++)printf("%d ", dense[i]);printf("\n");
}// A function to find intersection of two sets
SSet* SSet::intersection(SSet &s)
{// Capacity and max value of result setint iCap = min(n, s.n);int iMaxVal = max(s.maxValue, maxValue);// Create result setSSet *result = new SSet(iMaxVal, iCap);// Find the smaller of two sets// If this set is smallerif (n < s.n){// Search every element of this set in 's'.// If found, add it to resultfor (int i = 0; i < n; i++)if (s.search(dense[i]) != -1)result->insert(dense[i]);}else{// Search every element of 's' in this set.// If found, add it to resultfor (int i = 0; i < s.n; i++)if (search(s.dense[i]) != -1)result->insert(s.dense[i]);}return result;
}// A function to find union of two sets
// Time Complexity-O(n1+n2)
SSet* SSet::setUnion(SSet &s)
{// Find capacity and maximum value for result// set.int uCap = s.n + n;int uMaxVal = max(s.maxValue, maxValue);// Create result setSSet *result = new SSet(uMaxVal, uCap);// Traverse the first set and insert all// elements of it in result.for (int i = 0; i < n; i++)result->insert(dense[i]);// Traverse the second set and insert all// elements of it in result (Note that sparse// set doesn't insert an entry if it is already// present)for (int i = 0; i < s.n; i++)result->insert(s.dense[i]);return result;
}// Driver program
int main()
{// Create a set set1 with capacity 5 and max// value 100SSet s1(100, 5);// // Insert elements into the set set1s1.insert(5);s1.insert(3);s1.insert(9);s1.insert(10);// Printing the elements in the data structure.printf("The elements in set1 are\n");s1.print();int index = s1.search(3);// 'index' variable stores the index of the number to// be searched.if (index != -1) // 3 existsprintf("\n3 is found at index %d in set1\n",index);else         // 3 doesn't existprintf("\n3 doesn't exists in set1\n");// Delete 9 and print set1s1.deletion(9);s1.print();// Create a set with capacity 6 and max value// 1000SSet s2(1000, 6);// Insert elements into the sets2.insert(4);s2.insert(3);s2.insert(7);s2.insert(200);// Printing set 2.printf("\nThe elements in set2 are\n");s2.print();// Printing the intersection of the two setsSSet *intersect = s2.intersection(s1);printf("\nIntersection of set1 and set2\n");intersect->print();// Printing the union of the two setsSSet *unionset = s1.setUnion(s2);printf("\nUnion of set1 and set2\n");unionset->print();return 0;
}

[翻译转载] Sparse Set 稀疏集相关推荐

  1. android studio的GearVR应用开发(二)、一个简单的VR app(Oculus官方GearVR开发教程,翻译转载)

    声明:本文是Oculus官方的GearVR开发教程,为本人翻译转载,供广大VR开发爱好者一同学习进步使用. 原文章 一个简单的VR app 概观 在搭建好GearVR框架后,让我们一起来创建第一个VR ...

  2. Jinja2学习笔记暨官方文档的翻译 -- 转载

    为什么80%的码农都做不了架构师?>>>    呵呵, 刚刚看完Python模板引擎Jinja2的文档, 感觉很好, 觉得动态语言真是很好.  模板引擎竟然可以做的如此灵活....真 ...

  3. 【翻译转载】【官方教程】Asp.Net MVC4入门指南(2):添加一个控制器

    2. 添加一个控制器 · 原文地址:http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-c ...

  4. 多模态机器学习综述翻译(转载)

    文章:<Multimodal Machine Learning: A Survey and Taxonomy> 多模态机器学习综述 [摘要]我们对世界的体验是多模式的 - 我们看到物体,听 ...

  5. 论文翻译 SGCN:Sparse Graph Convolution Network for Pedestrian Trajectory Prediction 用于行人轨迹预测的稀疏图卷积网络

    SGCN:Sparse Graph Convolution Network for Pedestrian Trajectory Prediction 用于行人轨迹预测的稀疏图卷积网络 行人轨迹预测是自 ...

  6. cordova 调用蓝牙_ionic蓝牙插件(cordova-plugin-ble-central)(个人翻译转载请注明)

    支持:iOS和Android4.3+ 安装:Cordova PhoneGap API: scan 扫描: 蓝牙扫描的方法,第二个参数10指的扫描时间,单位是秒,device是扫描的设备 ble.sca ...

  7. haxe 第一期 入门骗 (谷歌翻译+转载)

    /*     欢迎在15分钟内学习Haxe 3.http://www.haxe.org     这是一个可执行的教程.    您可以使用haxe编译器编译并运行它,    而在与LearnHaxe.h ...

  8. Martin Fowler 微服务的原文翻译(转载)

    微服务 原文地址:Martin Fowler 微服务的原文 一个新的架构术语 "微服务架构"一词是在过去几年里涌现出来的,它用于描述一种独立部署的软件应用设计方式.这种架构方式并没 ...

  9. [翻译/转载] 部分使用intel RST硬盘驱动与电脑安装Linux系列系统相互冲突 导致无法装linux系统的解决方法

    (强烈建议翻墙,国内网站垃圾,啥都没有,全都是一群复制粘贴的垃圾水贴) 前言: 如果想直接看如何操作, 跳转文末按照 "1.2.3.4"操作即可 最开始参考的官方提供的解决方案链接 ...

最新文章

  1. 综合技术--maven的基本使用
  2. linux内核技术文章
  3. hibernate 向数据库里设置了默认值的字段添加数据为null时失效的问题
  4. 字符串中统计单词个数
  5. java equals 区别_Java中equals和==的区别
  6. python 类的功能,字符串字节,嵌套等相关学习总结
  7. html中加入js,html嵌入js
  8. python爬虫的数据如何解决乱码_写爬虫时如何解决网页乱码问题
  9. Android新手入门2016(14)--FragmentTabHost实现选项卡和菜单
  10. What's new document web part for SharePoint v1.1 [Free]
  11. elasticsearch(七)java 搜索功能Search Request的介绍与使用
  12. 微信小程序微商城:开发者key获取
  13. Unity - Windows获取屏幕分辨率、可用区域
  14. 分享Python入门经典基础题(day1)附完整答案
  15. webstorm汉化怎样切回英文_webstorm 单词快捷翻译设置
  16. 左神数据结构与算法(基础提升)——01
  17. 效率低?响应慢?报表工具痛点及其解决方案
  18. android进入recovery模式,Android关机重启至recovery安卓进入Recovery模式模式
  19. 计算机usb无法使用,Win7系统电脑USB接口无法使用解决方案
  20. request Headers字段详解

热门文章

  1. 计算机考研复试看脸吗,考研经验:考研复试也看脸,颜值也是蛮拼的
  2. vue的跳转(打开新页面)
  3. 手写数字识别环境安装(pytorch)(window10)
  4. 转:IBM ThinkPad笔记本电脑问题集
  5. 爬虫实战 -- (爬取证券期货市场失信记录平台)
  6. A. Log Chopping
  7. 群多多社群人脉H5-2.1.4多开插件+小程序独立前端+搭建教程
  8. 【图书推荐】云计算热潮来袭,你还能如此淡定吗?
  9. Facebook Cookbook: Building Applications to Grow Your Facebook Empire
  10. sadasddddddd