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)
 class MyHashSet {
final ListNode[] nodes = new ListNode[];
/** Initialize your data structure here. */
public MyHashSet() { } public void add(int key) {
int i = idx(key);
ListNode first = nodes[i];
if (first == null) {
nodes[i] = new ListNode(key);
} else if (!exists(first, key)) {
ListNode newNode = new ListNode(key);
newNode.next = nodes[i];
nodes[i] = newNode;
}
} public void remove(int key) {
int i = idx(key);
if (nodes[i] == null) {
return;
}
ListNode current = nodes[i];
ListNode previous = null;
while (current != null) {
if (current.key == key) {
if (previous != null) {
previous.next = current.next;
} else {
nodes[i] = current.next;
}
break;
} else {
previous = current;
current = current.next;
}
}
} /** Returns true if this set contains the specified element */
public boolean contains(int key) {
int i = idx(key);
ListNode first = nodes[i];
if (first == null) {
return false;
}
return exists(first, key);
} int idx(int key) {
return key % nodes.length;
} private boolean exists(ListNode node, int key) {
ListNode current = node;
while (current != null) {
if (current.key == key) {
return true;
}
current = current.next;
}
return false;
}
} class ListNode {
int key;
ListNode next; ListNode(int key) {
this.key = key;
}
}

最新文章

  1. 大数据实践-数据同步篇tungsten-relicator(mysql->mongo)
  2. 【BZOJ 3642】Phi的反函数
  3. 微信分享接口SDK简介使用
  4. mina2线程详解
  5. 关于Go,你可能不注意的7件事(转的)
  6. 【转】android程序编译过程
  7. 出现 could not open jvm.cfg 的解决办法
  8. AMQ学习笔记 - 15. 实践方案:基于ActiveMQ的统一日志服务
  9. C#中 ? 和?? 的用法
  10. Objective-C基础笔记一
  11. hive 中的Sort By、 Order By、Cluster By、Distribute By 区别
  12. Android零碎知识点总结
  13. Using CrunchBase API
  14. Jquery操作Table
  15. Java 网络 IO 模型
  16. Hadoop之Secondary NameNode
  17. Doctype知识点总结
  18. 支付宝沙箱测试-ALI40247
  19. linux-git
  20. Lavarel Route::resource

热门文章

  1. keydown([[data],fn]) 当键盘或按钮被按下时,发生 keydown 事件。
  2. 010_STM32程序移植之_lib库建立
  3. struts1 action之间的跳转
  4. 使用sysbench对MySQL进行压力测试
  5. Dynamic Data linq to SQL Web Application
  6. 无缓存I/O操作和标准I/O文件操作区别
  7. Robot Framework(十七) 扩展RobotFramework框架——扩展Robot Framework Jar
  8. Mac 卸载Python3.6
  9. MySQL的那些坑
  10. PHP学习之图像处理-水印类