Solve the problem of sparse 2- dimensional array
A sparse array is an array in which most of the elements have the same value (known
as the default value—usually 0 or null). The occurrence of zero elements in a large
array is inefficient for both computation and storage. It is required to implement
sparse 2- dimensional array in more efficient way. Your implementation should
allow:
Adding new value in a specific index.
Removing a value from specific index.
Search for a value and return its index if found.
Return a value from specific index.
#include <iostream>
#include <map>
#include <pair>
using namespace std;
class SparseArray {
private:
map<pair<int,int>,int> elems;
public:
void set(int, int, int);
void remove(int, int);
pair<int,int> find(int);
int get(int, int);
};
void SparseArray::set(int x, int y, int item) {
pair<int,int> p = {x, y};
auto iter = this->elems.find(p);
if (iter != this->elems.end()) {
this->elems[p] = item;
} else {
this->elems.insert(p, item);
}
}
void SparseArray::remove(int x, int y) {
pair<int,int> p = {x, y};
auto iter = this->elems.find(p);
if (iter != this->elems.end()) {
this->elems.erase(iter);
}
}
pair<int,int> SparseArray::find(int item) {
for (auto it = this->elems.begin(); it != this->elems.end(); it += 1) {
if ((*it).second == item) {
return (*it).first;
}
}
return NULL;
}
int SparseArray::get(int x, int y) {
pair<int,int> p = {x, y};
auto iter = this->elems.find(p);
if (iter != this->elems.end()) {
return (*iter).second;
} else {
return -1;
}
}
Comments
Leave a comment