面试题-查找一个数组是否存在数目大于一半的数
来源:互联网 发布:思科交换机端口聚合 编辑:程序博客网 时间:2024/05/14 04:14
在此,我考虑两个思路:
第一个就是naive的,直接统计就是,扫一遍计数hash_map。不多说
第二个就是先排序,然后找到中位数,只要存在这样的数,那么就是该中位数。统计该数的值就行
void quicksort(int a[], int begin, int end){if(begin>=end)return;int pivot = a[begin];int b = begin, e = end;int mid = 0;while(begin < end){while(a[end] >= pivot && end > begin)--end;a[begin] = a[end];while(a[begin] <= pivot && begin < end)++begin;a[end] = a[begin];}mid = begin;a[mid] = pivot;quicksort(a, b, mid-1);quicksort(a, mid+1,e);}
int getMoreThanHalfNumber(int a[], int len){quicksort(a, 0, len-1);int median = a[len/2];int count = 0;for(int i=0; i<len; i++){if(median == a[i])count++;}if(count > len/2)return median;return -1;}
如果只是找出数组中出现次数超过一半的数,则
int getMoreThanHalfNumberture(int a[], int len){int count = 1; int halfNumber = a[0];for(int i=1; i<len; i++){ if(a[i] == halfNumber)++count;else--count;if(count==0){halfNumber = a[i];count = 1;}}return halfNumber;}
- 面试题-查找一个数组是否存在数目大于一半的数
- 查找一个数是否存在于一个数组中。该数组分两段有序,第一段的数都大于第二段的数。
- 给定一个数组,从中查找是否存在两个数的和等于一个给定的x
- 二维数组中查找一个数是否存在
- 二维数组中查找是否存在一个数
- 在一个按行列递增的二维数组中查找一个数是否存在
- 面试题:检查一个数组里是否存在m个数的和等于某个值
- 遍历数组查找其中数字出现次数大于一半的
- 求出现次数大于数组长度一半的那个数
- 查找矩阵中是否存在一个数
- 海量数据查找一个数是否存在
- 《剑指Offer》面试题:超过数组长度的一半的数
- ZZ一道百度面试题:求数组中出现次数超过一半的数
- 百度面试题:找出数组中出现次数超过一半的数
- 百度面试题:找出数组中出现次数超过一半的数
- 百度面试题:找出数组中出现次数超过一半的数
- 《剑指offer》——面试题29:数组中超过一半的数
- 腾讯面试题----判断一个数是否存在(大数据方面)
- 临时表
- UITableViewCell
- 组合模式的优点
- 计算机经典书籍
- 剑指Offer之左旋转字符串(Move!Move!!Move!!!)
- 面试题-查找一个数组是否存在数目大于一半的数
- 求数组连续最大和
- css style override
- MySQL ERROR 1045 : Access denied for user解决方法
- Migration Toolkit an error occured during the initialzation of the runtimes system.please make sure
- xcode 设置编码区背景颜色为淡绿色
- Ubuntu Server 12.10下安装配置PyDev
- Git for Windows 终端字体警告
- 视频: 千重浪Linux系统调试技术培训03-01_basic_cpu_interrupt