Thursday, February 28, 2013

Teris problem

http://www.careercup.com/question?id=14099679


#include<iostream>
#include<map>
#include<algorithm>

using namespace std;

typedef map<int,int> Map;

Map FindOverNth(int arr[],int size,int n)
{
Map ret_map;
typedef Map::value_type Elem;
int total=0;
for_each(arr,arr+size,[&,n](int val)
{
auto ret_pair=ret_map.insert(Elem(val,0)); //no duplicates!
++(*ret_pair.first).second;++total;
if(ret_map.size()==n)
{
for(auto iter=ret_map.begin();iter!=ret_map.end();)
{
--(*iter).second;
--total;
if((*iter).second==0)
ret_map.erase(iter++);
else
iter++;
}
}
});
for_each(ret_map.begin(),ret_map.end(),[](Elem &elem){elem.second=0;});
for_each(arr,arr+size,[&ret_map](int val){if(ret_map.find(val)!=ret_map.end())ret_map[val]++;});
for(auto iter=ret_map.begin();iter!=ret_map.end();)
{
if((*iter).second<=size/n)
ret_map.erase(iter++);
else
iter++;
}
return ret_map;

}

No comments:

Post a Comment