# MoreThanHalfNumber

37人阅读 评论(0)

#include<stdio.h>
int Partition(int *number,int low,int high){
int pivot=number[low];
while(low<high){
while(low<high&&number[high]>=pivot) high--;
number[low]=number[high];
while(low<high&&number[low]<=pivot) low++;
number[high]=number[low];
}
number[low]=pivot;
return low;
}
bool CheckMorethanHalfNumber(int *number,int length,int key){
int times=0;
for(int i=0;i<length;i++)
if(number[i]==key)
times++;
if(2*times>length) return true;
return false;
}
int MoreThanHalfNumber(int *number,int length){
if(number==NULL||length<=0)
return 0;
int low=0;
int high=length-1;
int middle=length>>1;
int index=Partition(number,low,high);
while(index!=middle){
if(index<middle)
index=Partition(number,index+1,high);
else
index=Partition(number,low,index-1);
}
int result=number[index];
if(CheckMorethanHalfNumber(number,length,result))
return result;
return 0;
}
int MoreThanHalfNumberAgain(int *number,int length){
if(number==NULL|| length<=0)
return 0;
int times=1;
int key=number[0];
for(int i=1;i<length;i++){
if(number[i]==key)
times++;
else if(times==0){
key=number[i];
times=1;
}
else times--;
}
if(CheckMorethanHalfNumber(number,length,key))
return key;
return 0;
}



0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：47068次
• 积分：1527
• 等级：
• 排名：千里之外
• 原创：100篇
• 转载：74篇
• 译文：0篇
• 评论：2条
最新评论