Design a HashSet without using any built-in hash table libraries.

To be specific, your design should include these functions:

  • add(value): Insert a value into the HashSet.
  • contains(value) : Return whether the value exists in the HashSet or not.
  • remove(value): Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing.

Example:

MyHashSet hashSet = new MyHashSet();
hashSet.add(1);        
hashSet.add(2);        
hashSet.contains(1);    // returns true
hashSet.contains(3);    // returns false (not found)
hashSet.add(2);          
hashSet.contains(2);    // returns true
hashSet.remove(2);          
hashSet.contains(2);    // returns false (already removed)

Note:

    • All values will be in the range of [0, 1000000].
    • The number of operations will be in the range of [1, 10000].
    • Please do not use the built-in HashSet library.

这道题让我们设计HashSet,不能用自带的哈希表的数据结构,而且要我们主要实现添加,删除,以及判断是否存在,这三个函数。我们都知道HashSet最有用的地方就是其能够在常数的时间内判断某个元素是否存在,这都得归功于哈希表的作用。但是现在不让我们用了,但我们还是得保证其常数级的查找效率,那么就用空间来换时间吧。既然题目中说了数字的范围不会超过1000000,那么我们就申请这么大空间的数组,这样对于在HashSet中的数字,我们就将其标记为1,不在或者删除了的就标记为0,检测的时候就看其值是否为1即可,参见代码如下:

解法一:

class MyHashSet {
public:
/** Initialize your data structure here. */
MyHashSet() {
data.resize(, );
} void add(int key) {
data[key] = ;
} void remove(int key) {
data[key] = ;
} /** Returns true if this set contains the specified element */
bool contains(int key) {
return data[key] == ;
} private:
vector<int> data;
};

我们可以来适度的优化一下空间复杂度,由于存入HashSet的数字也许不会跨度很大,那么直接就申请长度为1000000的数组可能会有些浪费,那么我们其实可以使用1000个长度为1000的数组来代替,那么就要用个二维数组啦,实际上开始我们只申请了1000个空数组,对于每个要处理的元素,我们首先对1000取余,得到的值就当作哈希值,对应我们申请的那1000个空数组的位置,在加入元素时,一旦计算出了哈希值,我们将对应的空数组resize为长度1000,然后根据哈希值和key/1000来确定具体的加入位置。移除数字一样的,先计算出哈希值,如果对应的数组不为空的话,找到对应的位置并赋值为0。不过大家也可以看出来,我们在加入元素时会开辟1000的新空间,但是删除这个元素时,并没有检测这1000个位置是否均为0,是的话应该删除这1000个新空间。但是这样可能会使得删除函数变慢一些,参见代码如下:

解法二:

class MyHashSet {
public:
/** Initialize your data structure here. */
MyHashSet() {
data.resize(, vector<int>());
} void add(int key) {
int hashKey = key % ;
if (data[hashKey].empty()) {
data[hashKey].resize();
}
data[hashKey][key / ] = ;
} void remove(int key) {
int hashKey = key % ;
if (!data[hashKey].empty()) {
data[hashKey][key / ] = ;
}
} /** Returns true if this set contains the specified element */
bool contains(int key) {
int hashKey = key % ;
return !data[hashKey].empty() && data[hashKey][key / ];
} private:
vector<vector<int>> data;
};

类似题目:

Design HashMap

参考资料:

https://leetcode.com/problems/design-hashset/

https://leetcode.com/problems/design-hashset/discuss/185826/C%2B%2B-solution

https://leetcode.com/problems/design-hashset/discuss/193132/Solution-without-boolean-array

https://leetcode.com/problems/design-hashset/discuss/143434/Beats-100-Real-Java-Solution-(Not-boolean-array)

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Design HashSet 设计HashSet的更多相关文章

  1. [LeetCode] Design HashMap 设计HashMap

    Design a HashMap without using any built-in hash table libraries. To be specific, your design should ...

  2. [LeetCode] Design Twitter 设计推特

    Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and ...

  3. [LeetCode] Design Tic-Tac-Toe 设计井字棋游戏

    Design a Tic-tac-toe game that is played between two players on a n x n grid. You may assume the fol ...

  4. [LeetCode] Design TinyURL 设计精简URL地址

    Note: For the coding companion problem, please see: Encode and Decode TinyURL. How would you design ...

  5. LeetCode 622:设计循环队列 Design Circular Queue

    LeetCode 622:设计循环队列 Design Circular Queue 首先来看看队列这种数据结构: 队列:先入先出的数据结构 在 FIFO 数据结构中,将首先处理添加到队列中的第一个元素 ...

  6. LeetCode初级算法--设计问题01:Shuffle an Array (打乱数组)

    LeetCode初级算法--设计问题01:Shuffle an Array (打乱数组) 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:h ...

  7. LeetCode初级算法--设计问题02:最小栈

    LeetCode初级算法--设计问题02:最小栈 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.net ...

  8. 使用MATLAB 2019 App Design 工具设计一个 电子日记App

    使用MATLAB 2019 App Design 工具设计一个 电子日记App1.1 前言:由于信号与系统课程需要,因此下载了MATLAB软件,加之对新款的执着追求,通过一些渠道,下载了MATLAB ...

  9. Design Principle vs Design Pattern 设计原则 vs 设计模式

    Design Principle vs Design Pattern设计原则 vs 设计模式 来源:https://www.tutorialsteacher.com/articles/differen ...

随机推荐

  1. DirectX11 With Windows SDK--06 DirectXMath数学库

    前言 xnamath.h原本是位于DirectX SDK的一个数学库,但是现在Windows SDK包含的数学库已经抛弃掉原来的xnamath.h,并演变成了现在的DirectXMath.h.其实本质 ...

  2. 第一节:从面向对象思想(oo)开发、接口、抽象类以及二者比较

    一. 面向对象思想 1. 面向过程(OP)和面向对象(OO)的区别: (1):面向过程就是排着用最简单的代码一步一步写下去,没有封装,当业务复杂的时候,改动就很麻烦了 (2):面向对象将复杂的业务分离 ...

  3. react实战项目开发(2) react几个重要概念以及JSX语法

    前言 前面我们已经学习了利用官方脚手架搭建一套可以应用在生产环境下的React开发环境.那么今天这篇文章主要先了解几个react重要的概念,以及讲解本文的重要知识JSX语法 React重要概念 [思想 ...

  4. 2017-2018-2 PDE 讨论班

    等等. 第一次上课居然忘记怎么让笔记本电脑和投影仪相连了. 有两个接口. 一个在外面, 没用. 一个盖着了, 忘记翻开了.

  5. Collections of Zujin Zhang's Published works

    I am not good, but I shall do my best to be better. Any questions, please feel free to contact zhang ...

  6. oracle数据库驱动(ojdbc)

    第1部分 Q:为什么oralce的jdbc驱动,在maven上搜索到把pom配置复制到pom.xml里进行引用的时候会报错? ANS:虽然能在maven仓库里搜索到,但貌似不能用,原因是oracle是 ...

  7. 【js课设】电子画板01

    这学期web开发课的课设选了电子画板课题.(人家本来想做富文本编辑器的嘛然鹅老师在第二版里把这题删掉了。゚ヽ(゚´Д`)ノ゚。) 主要考虑的有[界面美观][画笔类型][画布分层]这三个点了. [界面美 ...

  8. Mysq登陆后执行命令提示You must SET PASSWORD before executing this statement

    mysql  安装完成后,在输入命令行时,提示:You must SET PASSWORD before executing this statement 提示必须设置密码,我想不是已经设置了密码吗? ...

  9. AC自动机算法详解 (转载)

    首先简要介绍一下AC自动机:Aho-Corasick automation,该算法在1975年产生于贝尔实验室,是著名的多模匹配算法之一.一个常见的例子就是给出n个单词,再给出一段包含m个字符的文章, ...

  10. word20161226

    1. condensed 英[kən'denst]美[kənˈdɛnst]v. (使) 变稠或变浓,浓缩( condense的过去式和过去分词 ); (使) 凝结; 简说,摘要,简述;[例句]The ...