-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRandomHash.cpp
More file actions
90 lines (84 loc) · 2.06 KB
/
RandomHash.cpp
File metadata and controls
90 lines (84 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>
#include <vector>
#include <unordered_map>
#include <time.h>
using namespace std;
// http://www.geeksforgeeks.org/design-a-data-structure-that-supports-insert-delete-search-and-getrandom-in-constant-time/
// Implement HashTable with get,set,delete,getRandom in O(1) Time
/*
a) Insert
b) Delete
c) Search
d) getRandom */
class RandomHash{
private:
vector<int> array; // store data value
unordered_map<int, int> map; // map from value -> array index
void swap(vector<int> &A, int p, int q){
int tmp = A[p];
A[p] = A[q];
A[q] = tmp;
}
public:
RandomHash(){}
void add(int val){
if(map.find(val) != map.end()){
// if already exist, do nothing
return;
}
array.push_back(val);
map[val] = array.size()-1;
}
void remove(int val){
if(map.find(val) == map.end()){
// do not exist
return;
}
int index = map[val];
swap(array, index, array.size()-1); //swap the one(to be deleted) with the last in array
array.pop_back(); // delete the last element in the array
map.erase(val); // remove the element in the hash table
map[array[index]] = index; // update the index in the hash
}
// return the index
int search(int val){
if(map.find(val) == map.end()){
return -1;// don't find
}
return map[val];
}
int getRandom(){
srand((unsigned)time(NULL));
int index = rand() % array.size();
return array[index];
}
int size(){
return array.size();
}
};
int main(void){
RandomHash hash;
hash.add(2);
hash.add(9);
hash.add(10);
hash.add(6);
cout<<"Hash size : "<<hash.size()<<endl;
hash.remove(10);
cout<<"Hash size : "<<hash.size()<<endl;
cout<<"Random test "<<endl;
for(int i = 0; i < 5; i++){
int val = hash.getRandom();
cout<<"Get Random index = "<< hash.search(val)<<", value =" << val <<endl;
}
for(int i = 0; i < 10; i++){
srand((unsigned)time(NULL));
int val = rand() % 10;
if(hash.search(val) == -1){
cout<<"Not found : "<<val<<endl;
}
else {
cout<<"We found : "<<val<<endl;
}
}
return 0;
}