|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +/** |
| 7 | + * 705. Design HashSet |
| 8 | + * |
| 9 | + * Design a HashSet without using any built-in hash table libraries. |
| 10 | + * |
| 11 | + * To be specific, your design should include these functions: |
| 12 | + * |
| 13 | + * add(value): Insert a value into the HashSet. |
| 14 | + * contains(value) : Return whether the value exists in the HashSet or not. |
| 15 | + * remove(value): Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing. |
| 16 | + * |
| 17 | + * Example: |
| 18 | + * |
| 19 | + * MyHashSet hashSet = new MyHashSet(); |
| 20 | + * hashSet.add(1); |
| 21 | + * hashSet.add(2); |
| 22 | + * hashSet.contains(1); // returns true |
| 23 | + * hashSet.contains(3); // returns false (not found) |
| 24 | + * hashSet.add(2); |
| 25 | + * hashSet.contains(2); // returns true |
| 26 | + * hashSet.remove(2); |
| 27 | + * hashSet.contains(2); // returns false (already removed) |
| 28 | + * |
| 29 | + * Note: |
| 30 | + * |
| 31 | + * All values will be in the range of [0, 1000000]. |
| 32 | + * The number of operations will be in the range of [1, 10000]. |
| 33 | + * Please do not use the built-in HashSet library. |
| 34 | + */ |
| 35 | +public class _705 { |
| 36 | + public static class Solution1 { |
| 37 | + class MyHashSet { |
| 38 | + Map<Integer, Integer> map; |
| 39 | + |
| 40 | + /** Initialize your data structure here. */ |
| 41 | + public MyHashSet() { |
| 42 | + map = new HashMap<>(); |
| 43 | + } |
| 44 | + |
| 45 | + public void add(int key) { |
| 46 | + map.put(key, 0); |
| 47 | + } |
| 48 | + |
| 49 | + public void remove(int key) { |
| 50 | + if (map.containsKey(key)) { |
| 51 | + map.remove(key); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + /** Returns true if this set contains the specified element */ |
| 56 | + public boolean contains(int key) { |
| 57 | + return map.containsKey(key); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments