leetcode【705】设计哈希集合

电玩女神 2021-10-03 01:48 329阅读 0赞

不使用任何内建的哈希表库设计一个哈希集合

具体地说,你的设计应该包含以下的功能

add(value):向哈希集合中插入一个值。
contains(value) :返回哈希集合中是否存在这个值。
remove(value):将给定值从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。

解题思路:利用LinkedList进行哈希桶的设计,因为LinkedList自带头插方法,在jdk1.7之前都是头插,jdk1.8之后都是进行尾插。然后用valueOf方法进行判断是否含有。

  1. class MyHashSet {
  2. private Bucket[] buckets;
  3. private int key_space;
  4. /** Initialize your data structure here. */
  5. public MyHashSet() {
  6. this.key_space = 1024;
  7. buckets = new Bucket[key_space];
  8. for(int i = 0;i<key_space;i++)
  9. buckets[i] = new Bucket();
  10. }
  11. public void add(int key) {
  12. int index = key%key_space;
  13. buckets[index].insert(key);
  14. }
  15. public void remove(int key) {
  16. int index = key%key_space;
  17. buckets[index].delete(key);
  18. }
  19. /** Returns true if this set contains the specified element */
  20. public boolean contains(int key) {
  21. int index = key%key_space;
  22. return buckets[index].exist(key);
  23. }
  24. }
  25. class Bucket{
  26. private LinkedList<Integer> mybucket;
  27. public Bucket(){
  28. mybucket = new LinkedList<>();
  29. }
  30. public void insert(int key){
  31. int index = mybucket.indexOf(key);
  32. if(index == -1)
  33. mybucket.addFirst(key);
  34. }
  35. public void delete(Integer key){
  36. mybucket.remove(key);
  37. }
  38. public boolean exist(Integer key){
  39. int index = mybucket.indexOf(key);
  40. return index!=-1;
  41. }
  42. }

发表评论

表情:
评论列表 (有 0 条评论,329人围观)

还没有评论,来说两句吧...

相关阅读