forked from piyush01123/Daily-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sol.cpp
55 lines (48 loc) · 947 Bytes
/
sol.cpp
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
#include <iostream>
#include <map>
class SparseArray{
// sparse array data structure based on map
public:
SparseArray(int);
void set(int, int);
int get(int);
std::map<int, int> H;
int size;
};
SparseArray::SparseArray(int size){
// constructor
this->size = size;
}
void SparseArray::set(int i, int val){
// set method
if (i>=this->size || i<0 ){
std::cout << "Invalid Index" << std::endl;
return;
}
this->H[i] = val;
return;
}
int SparseArray::get(int i){
// get method
if (i<0 || i>=this->size){
std::cout << "Invalid Index" << std::endl;
return -1;
}
if (this->H.find(i) == this->H.end()){
return 0;
}
return this->H[i];
}
void test(){
// builds and runs test cases
SparseArray sa(100);
sa.set(1, 4);
std::cout << sa.get(6) << std::endl;
std::cout << sa.get(1) << std::endl;
std::cout << sa.get(101) << std::endl;
}
int main(){
// run the test
test();
return 0;
}