众数问题
来源:互联网 发布:linux svn回退版本号 编辑:程序博客网 时间:2024/06/05 17:58
#include "iostream"#include "algorithm"#include "fstream"using namespace std;//数组a[l,h]中,将小于a[l]的放其左,大于a[l]的放其右int partition(int y[], int l, int r){ int i = l, j = r+1; int x = y[l]; while(true) { while(y[++i] < x); while(y[--j] > x); if(i>=j) break; swap(y[i], y[j]); } y[l] = y[j]; y[j] = x; return j; }//统计a[mid]出现的次数//minIndex记录a[mid]最左边下标,maxIndex记录a[mid]最右边下标int modeIndex(int a[], int &mid, int l, int h, int &minIndex, int &maxIndex){ int left = mid; int right = mid; while(a[--left] == a[mid] && left>=l); while(a[++right] == a[mid] && right<=h); left++; right--; minIndex = left; maxIndex = right; return maxIndex - minIndex + 1;}//number为a[l,h]的众数,count为重数void mode(int a[], int l, int h, int &number, int &count){ int index = partition(a, l, h); //众数下标 int minIndex, maxIndex; int num = modeIndex(a, index, l, h, minIndex, maxIndex); //统计a[index]出现的次数num if(num > count) //如果a[mid]出现次数比之前找到的众数出现次数多 { number = a[index]; //更新众数 count = num; //更新众数的个数 } if(num < minIndex-l+1) //如果a[index]左边的数大于num,向左递归 mode(a, l, minIndex-1, number, count); if(num < h-maxIndex+1) //如果a[index]右边的数大于num,向右递归 mode(a, maxIndex+1, h, number, count);}int main(){ int n; ifstream fin("number.txt"); fin >> n; cout << "元素个数为:" << n << endl; int *a = new int[n+1]; cout << "各元素为:\n"; for(int i=1; i<=n; i++) { fin >> a[i]; cout << a[i] << " "; } sort(a, a+n); cout << endl; int count = 0; int number; mode(a, 1, n, number, count); cout << "众数为:" << number << endl; cout << "重数为:" << count << endl; fin.close(); return 0;}
0 0
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- MyEclipse快捷键大全
- forward内部跳转 和redirect重定向跳转的区别
- linux下清理mantis_email_table里数据堆积
- Spring学习笔记
- iOS证书(.p12)和描述文件(.mobileprovision)申请
- 众数问题
- 屏幕适配相关知识点
- Java基础编程之从控制台循环输入
- WdfRequestRetrieveOutputBuffer
- 解决启动PyCharm,报错No Python interpreter selected
- mysql学习——DATE_SUB()&EXTRACT() 函数
- mybatis使用${}出错
- 一个苹果证书如何多次使用——导出p12文件
- Tomcat server.xml配置示例