数组中出现次数超过一半的数字
来源:互联网 发布:智能小车pid算法 编辑:程序博客网 时间:2024/05/17 03:13
若数组中出现次数超过数组长度一半的数字,请找出这个数字。
#include <iostream>#include <algorithm>using namespace std;//检查输入的数组是否有效bool checkArray(int *a,int len){ if( a==NULL || len<=0){ return false; } return true;}//检查数组中的某个数字出现次数是否超过数组长度的一半bool checkMoreThanHalf(int *a,int len,int num){ int count=0; for(int i=0;i<len;i++){ if(num==a[i]){ count++; } } if(count*2>=len){ return true; } return false;}//首先想到的当然是排序int BySort(int *a,int len){ if(!checkArray(a,len)) return 0; sort(a,a+9); int res=a[len/2]; if(!checkMoreThanHalf(a,len,res)) return 0; return res;}//根据数组特点的方法int MoreThanHalfNum(int *a,int len){ if(!checkArray(a,len)){ return 0; } int res=a[0]; int times=1; for(int i=0;i<len;i++){ if(times==0){ res=a[i]; times++; } else if(res==a[i]){ times++; } else{ times--; } } if(!checkMoreThanHalf(a,len,res)) return 0; return res;}int main(){ int a[9]={1,2,3,2,2,2,5,4,2}; //cout<<"The number of "<<MoreThanHalfNum(a,9)<<" is more than half"<<endl; cout<<"The number of "<<BySort(a,9)<<" is more than half"<<endl; return 0;}
0 0
- 数组中超过出现次数超过一半的数字
- 74.数组中超过出现次数超过一半的数字
- 74 数组中超过出现次数超过一半的数字
- 【数组4】数组中出现次数超过一半的数字
- 数组4:数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 找出数组中出现次数超过长度一半的数字
- 2-数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字[算法]
- 数组中出现次数超过一半的数字
- 找出数组中出现次数超过一半的数字--百度
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 寻找数组中出现次数超过一半的数字
- 面试训练数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- MD5加密
- android预置apk
- 自定义布局实现自动换行
- 驱动开发之 Windows驱动编程基础教程(1.1-1.3)
- 什么是java序列化,如何实现java序列化?
- 数组中出现次数超过一半的数字
- 解決 Ubuntu fd0 錯誤 /dev/fd0 floppy drive
- oracle调优之sql语句
- centos关机与重启命令详解
- Android Map Api 使用和开发(2) 定位我的位置、地图弹出泡泡、通过经纬度获取地址
- 技术点详解---IPSec VPN基本原理
- 【SqlServer】跨服务器查询报错
- 出国体检 西安 USC
- alibaba