2014-05-02 10:47
原题:
Given an unordered array of positive integers, create an algorithm that makes sure no group of integers of size bigger than M have the same integers. Input: ,,,,,,,, M =
Output: ,,,,,,,,
题目:给定一个未排序的长度为N的整数数组,和一个正整数M。请设计算法,将N个数分成M个数一组,并且每一组都不包含重复元素。
解法:本题的要求是每个组不能出现重复的数,那么换句话说就是把重复的元素分到不同的组去。我们按打扑克时发牌的方式,将重复的牌聚在一起,然后轮流发给每个组,就能保证他们不出现在一组里了。要要重复的牌聚在一次,既可以通过排序,也可以通过哈希表来统计个数。
代码:
// http://www.careercup.com/question?id=6026101998485504
// Actually, I don't quite understand the problem. The poster of this problem gave it too vague..
#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <vector>
#include <xiosbase>
using namespace std; class Solution {
public:
void disperse(vector<int> &v, int m) {
int n = (int)v.size(); if (n <= ) {
return;
} int count;
unordered_map<int, int> um; int i; for (i = ; i < n; ++i) {
++um[v[i]];
} unordered_map<int, int>::iterator umit, umit2;
i = ;
while (!um.empty()) {
count = ;
umit = um.begin();
while (umit != um.end()) {
v[i++] = umit->first;
--(umit->second);
++count;
if (umit->second == ) {
// remove empty items to speed up the search.
umit2 = umit;
++umit;
um.erase(umit2);
} else {
++umit;
} if (count == m) {
// pick at most m distinct elements at each round.
break;
}
}
}
};
}; int main()
{
int n, m;
vector<int> v;
Solution sol;
int i; ios::sync_with_stdio(false); while (cin >> n && n > ) {
v.resize(n); for (i = ; i < n; ++i) {
cin >> v[i];
}
cin >> m;
sol.disperse(v, m);
for (i = ; i < n; ++i) {
i ? cout << ' ', : ;
cout << v[i];
}
cout << endl; v.clear();
} return ;
}