|
| 1 | +package com.leetcode.scala.monthly2020.august |
| 2 | + |
| 3 | +/* |
| 4 | +* Design a HashSet without using any built-in hash table libraries. |
| 5 | +* To be specific, your design should include these functions: |
| 6 | + * add(value): Insert a value into the HashSet. |
| 7 | + * contains(value) : Return whether the value exists in the HashSet or not. |
| 8 | + * remove(value): Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing. |
| 9 | +* */ |
| 10 | + |
| 11 | +/* |
| 12 | +* MyHashSet hashSet = new MyHashSet(); |
| 13 | + hashSet.add(1); |
| 14 | + hashSet.add(2); |
| 15 | + hashSet.contains(1); // returns true |
| 16 | + hashSet.contains(3); // returns false (not found) |
| 17 | + hashSet.add(2); |
| 18 | + hashSet.contains(2); // returns true |
| 19 | + hashSet.remove(2); |
| 20 | + hashSet.contains(2); // returns false (already removed) |
| 21 | +* |
| 22 | +* Note: |
| 23 | + * All values will be in the range of [0, 1000000]. |
| 24 | + * The number of operations will be in the range of [1, 10000]. |
| 25 | + * Please do not use the built-in HashSet library. |
| 26 | +* |
| 27 | +* */ |
| 28 | + |
| 29 | +/* |
| 30 | +* Approach: Using Big Array |
| 31 | +* 1. Since we know the range we can build array of boolean with the range and key will be the index of the array. |
| 32 | +* 2. But lot of space will be wasted. |
| 33 | +* */ |
| 34 | + |
| 35 | +class MyHashSet() { |
| 36 | + |
| 37 | + /** Initialize your data structure here. */ |
| 38 | + private var array: Array[Boolean] = Array.fill(1000001)(false) |
| 39 | + |
| 40 | + def add(key: Int): Unit = { |
| 41 | + array(key) = true |
| 42 | + } |
| 43 | + |
| 44 | + def remove(key: Int): Unit = { |
| 45 | + if (array(key)) { |
| 46 | + array(key) = false |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + /** Returns true if this set contains the specified element */ |
| 51 | + def contains(key: Int): Boolean = { |
| 52 | + return array(key) |
| 53 | + } |
| 54 | + |
| 55 | +} |
| 56 | + |
| 57 | +object DesignHashSet { |
| 58 | + |
| 59 | + def main(args: Array[String]): Unit = { |
| 60 | + val hashSet: MyHashSet = new MyHashSet() |
| 61 | + hashSet.add(1) |
| 62 | + hashSet.add(2) |
| 63 | + hashSet.contains(1) // returns true |
| 64 | + hashSet.contains(3) // returns false (not found) |
| 65 | + hashSet.add(2) |
| 66 | + hashSet.contains(2) // returns true |
| 67 | + hashSet.remove(2) |
| 68 | + hashSet.contains(2) // returns false (already removed) |
| 69 | + } |
| 70 | + |
| 71 | +} |
0 commit comments