找出数组中出现次数超过一半的数
来源:互联网 发布:python celery安装 编辑:程序博客网 时间:2024/05/17 15:40
如果有一个数出现的次数超过一半,那他出现的次数肯定比其他数字出现次数的和还要多,这时可以遍历数组并保存两个值,一个是出现的数字,一个是次数,当下一个数字和保存的数字相同时,次数加1,如果不同,次数减1,如果次数为0,我们需要保存下一个数字,并将次数设为1。最后保存的数字即为所求。同时考虑空数组和没有出现次数超过一半的情况。
class Solution {public: int MoreThanHalfNum_Solution(vector<int> numbers) { if(numbers.empty()) return 0; else{ int res=numbers[0]; int times=1; for(int i=1;i<numbers.size();++i){ if(times==0){ res=numbers[i]; times=0; } else if(numbers[i]==res) times++; else times--; } times =0; for(int i=0;i<numbers.size();++i){ if(numbers[i]==res) times++; } if(times*2<=numbers.size()) return 0; return res; } }};
基于Partition函数的O(n)算法
类似快排,选定一个基准,比它小的都在左边,比它大的都在右边,比如如果它的下标小于n/2,那中位数应该位于右边,继续在右边查找。这样就可以找出超过一半的数。
int Partition(int data[],int length,int start,int end){ int index=RandomInRange(start,end); swap(data[index],data[end]); int small=start-1; for(index=start;index<end;++index){ if(data[index]<data[end]){ ++small; if(small!=index) swap(data[index,data[small]); } } ++small; swap(data[small],data[end]); return small;}int MoreThanHalfNum(int *numbers,int length){ if(CheckInvalidArray(numbers,length)) return 0; int middle=length>>1; int start=0; int end=length-1; int index=Partition(numbers,length,start,end); while(index!=middle){ if(index>middle){ end=index-1; index=Partition(numbers,length,start,end); } else{ start=index+1; index=Partition(numbers,length,start,end); } } int result=numbers[middle]; if(!CheckMoreThanHalf(numbers,length,result) result=0; return result;}
CheckInvalidArray函数检查数组是否合法,CheckMoreThanHalf函数检查所得数字是否符合要求
0 0
- 找出数组中出现次数超过一半的数
- 算法--找出数组中出现次数超过一半的数
- 找出数组中出现次数超过一半的数
- 找出数组中出现次数超过一半的数
- 算法--找出数组中出现次数超过一半的数
- 找出数组中出现次数超过一半的数
- 找出数组中出现次数超过一半的数
- 算法--找出数组中出现次数超过一半的数
- 找出数组中出现次数超过一半的数
- 找出数组中出现次数超过一半的数
- 找出数组中出现次数超过一半的数
- 找出数组中出现次数超过一半的数
- 找出出现次数超过数组一半元素的数
- 找出数组出现次数超过一半的数
- 找出数组中出现次数超过数组长度一半的数
- 找出数组中出现次数超过长度一半的数字
- 找出数组中出现次数超过一半的数字--百度
- 找出数组中出现次数超过一半的数字
- CentOs mysql 的安装与默认安装目录修改
- 【NOIP2015】信息传递 CODE[VS] 4511
- 工作流系统之二十五 .net工作流系统开发体会
- Java基础中按值传递和引用传递详解
- Android OpenGLES2.0(四)——正方形和圆形
- 找出数组中出现次数超过一半的数
- Bit Operation
- set including path in mex
- Backpressure
- 工作流系统之二十六 .net工作流系统之扩展性
- 转发和重定向 HTTP请求方式
- JZOJ 4816. 【NOIP2016提高A组五校联考4】label
- 浙大 数据结构基础 week2 4-1
- 使用jQuery实现图片轮播的方法