我需要帮助找出数组中出现次数最少的元素。我想不出任何可靠的算法,C++ 库中是否定义了任何函数来执行此操作?
如果有你能想出的算法,请分享。不一定是代码,而是想法
“定义最少重复出现” - 假设数组 a[4]
包含 2,2,2,4
。 4
是最少出现的元素
最佳答案
为简洁起见使用了一些 C++14 特性,但很容易适应 C++11:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <unordered_map>
using namespace std;
template <typename I>
auto leastRecurring(I first, I last) {
unordered_map<iterator_traits<I>::value_type, size_t> counts;
for_each(first, last, [&counts](auto e) { ++counts[e]; });
return min_element(begin(counts), end(counts), [](auto x, auto y) { return x.second < y.second; })->first;
}
int main() {
const int a[] = {2, 2, 2, 3, 3, 4};
cout << leastRecurring(begin(a), end(a)) << endl;
}
关于c++ - 找出数组中出现次数最少的数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22410323/