MoreThanHalfNumber

原创 2016年08月31日 11:07:40
#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;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)