Suppose we have a vector like
a = {2,2,2,1,7,7,7,5,5}
I wish to get a sorted vector of unique elements which in this case gives
b = {1,2,5,7}
I also wish to get a vector of indexes of this sorted vector that reconstructs the initial vector:
c = {1,1,1,0,3,3,3,2,2}
Here b[x] for each element x in c returns the original vector a.
{ b[1],b[1],b[1],b[0],b[3],b[3],b[3],b[2],b[2] } = { 2,2,2,1,7,7,7,5,5 }
I wish to write an efficient algorithm in C++ to give me vectors b and c, given a vector a.
I have implemented a brute force solution below:
std::vector<int> vector_a{ 2,2,2,1,7,7,7,5,5 };
std::vector<int> vector_b(vector_a);
std::sort(vector_b.begin(), vector_b.end());
std::vector<int>::iterator ip;
ip = std::unique(vector_b.begin(), vector_b.end());
vector_b.resize(std::distance(vector_b.begin(), ip));
std::vector<int> vector_c;
for (int i = 0; i < vector_a.size(); ++i) {
for (int j = 0; j < vector_b.size(); ++j) {
if (vector_a[i] == vector_b[j]) {
vector_c.push_back(j);
}
}
}
Is there a way I can implement a more efficient solution with complexity lesser than O(m*n)?