2014-05-02 10:47
原题:
1 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. 2 3 Input: 2,1,1,1,3,4,4,4,5 M = 2 4 Output: 2,1,1,3,1,4,4,5,4
题目:给定一个未排序的长度为N的整数数组,和一个正整数M。请设计算法,将N个数分成M个数一组,并且每一组都不包含重复元素。
解法:本题的要求是每个组不能出现重复的数,那么换句话说就是把重复的元素分到不同的组去。我们按打扑克时发牌的方式,将重复的牌聚在一起,然后轮流发给每个组,就能保证他们不出现在一组里了。要要重复的牌聚在一次,既可以通过排序,也可以通过哈希表来统计个数。
代码:
1 // http://www.careercup.com/question?id=6026101998485504 2 // Actually, I don't quite understand the problem. The poster of this problem gave it too vague.. 3 #include <algorithm> 4 #include <iostream> 5 #include <unordered_map> 6 #include <vector> 7 #include <xiosbase> 8 using namespace std; 9 10 class Solution { 11 public: 12 void disperse(vector<int> &v, int m) { 13 int n = (int)v.size(); 14 15 if (n <= 1) { 16 return; 17 } 18 19 int count; 20 unordered_map<int, int> um; 21 22 int i; 23 24 for (i = 0; i < n; ++i) { 25 ++um[v[i]]; 26 } 27 28 unordered_map<int, int>::iterator umit, umit2; 29 i = 0; 30 while (!um.empty()) { 31 count = 0; 32 umit = um.begin(); 33 while (umit != um.end()) { 34 v[i++] = umit->first; 35 --(umit->second); 36 ++count; 37 if (umit->second == 0) { 38 // remove empty items to speed up the search. 39 umit2 = umit; 40 ++umit; 41 um.erase(umit2); 42 } else { 43 ++umit; 44 } 45 46 if (count == m) { 47 // pick at most m distinct elements at each round. 48 break; 49 } 50 } 51 } 52 }; 53 }; 54 55 int main() 56 { 57 int n, m; 58 vector<int> v; 59 Solution sol; 60 int i; 61 62 ios::sync_with_stdio(false); 63 64 while (cin >> n && n > 0) { 65 v.resize(n); 66 67 for (i = 0; i < n; ++i) { 68 cin >> v[i]; 69 } 70 cin >> m; 71 sol.disperse(v, m); 72 for (i = 0; i < n; ++i) { 73 i ? cout << ' ', 1 : 1; 74 cout << v[i]; 75 } 76 cout << endl; 77 78 v.clear(); 79 } 80 81 return 0; 82 }