您正在寻找一个具有非零重复计数的项目(模式 3)。我想我会递归地做:
- 将数组分成两半
- 查找每半个代表数非零(mod 3)的项目
- 合并两半,保留不相等键的计数,并添加相等键的计数
- 用 count = 0 (mod 3) 删除任何一个
- 将其作为输入当前部分的值集返回。
甚至没有尝试优化基本算法之外的东西(例如,不担心每个计数只存储两位),这似乎做得很好。我已经包含代码来生成一个相当大的测试用例(例如,1500 多个项目)并打印出它正在创建的地图的大小。在任何给定时间,它创建的地图中似乎最多有大约 50 个项目(即,它一次只使用两个地图,而我见过的最大项目是大约 25 个项目)。从技术上讲,目前我认为这类似于 O(N log N),但如果你切换到基于哈希的容器,我相信你会期望 O(N)。
#include <map>
#include <iterator>
#include <iostream>
#include <algorithm>
#include <utility>
#include <vector>
#include <time.h>
class zero_mod {
unsigned base;
public:
zero_mod(unsigned b) : base(b) {}
bool operator()(std::pair<int, int> const &v) {
return v.second % base == 0;
}
};
// merge two maps together -- all keys from both maps, and the sums
// of equal values.
// Then remove any items with a value congruent to 0 (mod 3)
//
std::map<int, int>
merge(std::map<int, int> const &left, std::map<int, int> const &right) {
std::map<int, int>::const_iterator p, pos;
std::map<int, int> temp, ret;
std::copy(left.begin(), left.end(), std::inserter(temp, temp.end()));
for (p=right.begin(); p!=right.end(); ++p)
temp[p->first] += p->second;
std::remove_copy_if(temp.begin(), temp.end(),
std::inserter(ret, ret.end()),
zero_mod(3));
return ret;
}
// Recursively find items with counts != 0 (mod 3):
std::map<int, int>
do_count(std::vector<int> const &input, size_t left, size_t right) {
std::map<int, int> left_counts, right_counts, temp, ret;
if (right - left <= 2) {
for (size_t i=left; i!=right; ++i)
++ret[input[i]];
return ret;
}
size_t middle = left + (right-left)/2;
left_counts = do_count(input, left, middle);
right_counts = do_count(input, middle, right);
ret = merge(left_counts, right_counts);
// show the size of the map to get an idea of how much storage we're using.
std::cerr << "Size: " << ret.size() << "\t";
return ret;
}
std::map<int, int> count(std::vector<int> const &input) {
return do_count(input, 0, input.size());
}
namespace std {
ostream &operator<<(ostream &os, pair<int, int> const &p) {
return os << p.first;
}
}
int main() {
srand(time(NULL));
std::vector<int> test;
// generate a bunch of data by inserting packets of 3 items
for (int i=0; i<100; i++) {
int packets = std::rand() % 10;
int value = rand() % 50;
for (int i=0; i<packets * 3; i++)
test.push_back(value);
}
// then remove one item, so that value will not occur a multiple of 3 times
size_t pos = rand() % test.size();
std::cerr << "Removing: " << test[pos] << " at position: " << pos << "\n";
test.erase(test.begin()+pos);
std::cerr << "Overall size: " << test.size() << "\n";
std::random_shuffle(test.begin(), test.end());
// Note that we use a map of results, so this will work if multiple values
// occur the wrong number of times.
std::map<int, int> results = count(test);
// show the results. Should match the value shown as removed above:
std::copy(results.begin(), results.end(),
std::ostream_iterator<std::pair<int, int> >(std::cout, "\n"));
return 0;
}