Merge Array
/***
In given array of elements like [a1,a2,a3,..an,b1,b2,b3,..bn,c1,c2,c3,...cn]
Write a program to merge them like [a1,b1,c1,a2,b2,c2,...an,bn,cn].
PS: Doing without using extra memory would fetch more points
Sample Testcases:
Input #00:
{1,2,3,4,5,6,7,8,9,10,11,12}
Output #00:
{1,5,9,2,6,10,3,7,11,4,8,12}
Explanation:
Here as you can notice, the array is of the form
{a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4}
***/
#include<iostream>
#include<string>
#include<map>
#include <vector>
using namespace std;
class mergeArray {
public:
mergeArray(string *str, int size);
~mergeArray();
void arrangementArray();
void print();
private:
map<int, vector<int>> mymap;
string *mystr;
int sz;
};
mergeArray::mergeArray(string *str, int size) {
mystr = str;
sz = size;
//initial map;
mymap.clear();
}
mergeArray::~mergeArray() {
mymap.clear();
}
void mergeArray::arrangementArray() {
map<int, vector<int>>::iterator it;
int id;
for(int i = 0; i<sz; i++) {
string s = mystr[i];
//Note: direct access the number..
id = atoi(s.c_str()+1);
it = mymap.find(id);
if(it != mymap.end()) {
it->second.push_back(i);
} else {
vector<int> v;
v.push_back(i);
mymap.insert(pair<int, vector<int>>(id, v));
}
}
}
void mergeArray::print() {
map<int, vector<int>>::iterator it;
for(it = mymap.begin(); it != mymap.end(); it++) {
vector<int> v = it->second;
for(int i = 0; i < v.size(); i++)
cout<<mystr[v[i]]<<" ";
}
cout<<endl;
}
void main() {
string str[] = {"a1","a2","a3","a4","b1","b2","b3","b4","c1","c2","c3","c4"};
int sz = sizeof(str) / sizeof(string);
mergeArray mga(str, sz);
mga.arrangementArray();
mga.print();
}
Space Complexity is O(n), should be done with O(1)...
ReplyDelete