找出出现次数最多的几个数值
来源:互联网 发布:c语言标准库函数及功能 编辑:程序博客网 时间:2024/06/04 17:55
这道题目所说的出现最多的几个数值,其实是带有附加条件的:
这几个数值中出现次数最少的那个数,要比除这几个值外的其他数的总个数要多。(说的自己都有点晕-_-!)
这样才能在最后结果中,呈现这几个数。所以必须按照数据源中的统计量分析出求前几位的数值。
其代码如下:
#include <iostream>#include <hash_map>using namespace std;void Find(int data[], int length, hash_map<int, int>& hMap,int id_count){ int min_index = -1; int min_temp = 0; for(int i = 0; i < length; i++) { //找到元素 if (hMap.find(data[i]) != hMap.end()) { hMap[data[i]]++; } else //没找到,进行抵消 { //初始化阶段 if(hMap.size() < id_count) { hMap[data[i]] = 1; min_index = data[i]; min_temp = 1; } else //进行抵消 { //找到最小索引 hash_map<int, int>::iterator it_end = hMap.end(); for (hash_map<int, int>::iterator it = hMap.begin(); it != it_end; it++) { if (it->second <= min_temp) { min_temp = it->second; min_index = it->first; break; } } if (hMap[min_index] == 1) { hMap.erase(min_index); } else { min_temp = --hMap[min_index]; } } } }}int main(){ //int data[] = {1, 2, 6, 2, 2, 4, 4, 3, 4, 2, 4}; int data[] = {3,4,5,3,6,1,3,4,4,5,2,4,5,3,5,}; int id_count = 3; hash_map<int, int> hMap; Find(data, sizeof(data) / sizeof(int), hMap, id_count); hash_map<int, int>::iterator it_end = hMap.end(); for (hash_map<int, int>::iterator it = hMap.begin(); it != it_end; it++) { cout << it->first << "is" << it->second << endl; } return 0;}
此程序时间复杂度为O(n),并用到了hash_map,为了能快速查找,这在较多数据时,性能提升比较明显。hash需要初始化桶的个数,因为hash的内存平均使用率为50%,再加上当超出hash范围时,需要平方重新分配空间,在工程中如不初始化桶的个数,程序经常会崩掉。
但windows中的hash_map并不需要初始化,由系统自行管理,这个有点诡异。
相对于本文的类似题目有:
找出数组中超过半数的数、超过1/3的两个最大数等等……
0 0
- 找出出现次数最多的几个数值
- 找出出现次数最多的数
- js找出字符出现的次数最多的字母
- 一次遍历找出“出现次数最多的子串”
- 找出数组中出现次数最多的数
- 找出一句话中出现次数最多的单词
- 找出一行字符串中的连续出现次数最多的字串
- 找出字符串中连续出现次数最多的子串
- 找出数组中出现次数最多的数字
- 找出出现次数最多的数字(需要考虑顺序)
- 找出数组里面元素出现次数最多的问题
- 找出数组里面元素出现次数最多的问题
- 找出数组中出现次数最多的子串
- 找出字符串中连续出现次数最多的子串
- 海量日志数据,找出出现次数最多的IP地址。
- 海量日志数据,找出出现次数最多的IP地址。
- 找出字符串中第一个出现次数最多的字符
- 找出字符串中第一个出现次数最多的字符
- 去除文本框中 html元素
- top命令详解
- OCP 1Z0 052 104
- 17 oj 对象转换
- leetcode - Generate Parentheses
- 找出出现次数最多的几个数值
- PHP文件上传
- URL传递值
- vmalloc分配高端物理内存
- Oracle11gR2创建表空间
- 某猿的饭局
- 如何推广自己的新网站
- android app 接入支付宝
- ext combobox动态加载数据库数据