MoreThanHalfNumber

#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;
}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014558484/article/details/52383000
个人分类: 剑指offer
上一篇ThreadLocal解析
下一篇KLastNumbers
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭