29 数组中出现数字超过一半的数字

描述:


实现代码:

package question29;

public class MoreThanHalfNumber {
  static   boolean inputInvalid=false;
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		
		int numbers[]={0,2,1,2,2,3,2,2,5,4,2};
		for (int i : numbers) {
			
		}
		int result=moreThanHalfNum(numbers,numbers.length);
		
		System.out.println(result);
	}

	

	private static int moreThanHalfNum(int[] numbers,int len) {
		// TODO Auto-generated method stub
		if (CheckInvalidArray(numbers,len)) {
			return 0;
		}
		
		int mid=len>>1;
		int start=0;
		int end=len-1;
		int index=partition(numbers,len,start,end);
		while (index!=mid) {
			if (index>mid) {
				end=index-1;
				index=partition(numbers, len, start, end);
			}else {
				start=index+1;
				index=partition(numbers, len, start, end);
			}
		}
		
		int result=numbers[mid];
		if (!CheckMoreThanHalf(numbers,len,result)) {
			result=0;
		}
		
		return result;
		
		
	}

	private static boolean CheckMoreThanHalf(int[] numbers, int len, int result) {
		// TODO Auto-generated method stub
		int times=0;
		for (int i = 0; i < numbers.length; i++) {
			if (numbers[i]==result) {
				times++;
			}
		}
		boolean isMoreThanHalf=true;
		if (times*2<=len) {
			inputInvalid=true;
			isMoreThanHalf=false;
		}
		return isMoreThanHalf;
	}

	private static int partition(int[] numbers, int len, int left, int right) {
		// TODO Auto-generated method stub
		int i=left;
		int j=right;
		int key=numbers[left];
		
		while (i<j) {
			while (i<j&&numbers[j]>=key)  j--;
			numbers[i]=numbers[j];
			while (i<j&&numbers[i]<=key)  i++;
			numbers[j]=numbers[i];
		}
		numbers[i]=key;
		return i;
	}

	private static boolean CheckInvalidArray(int[] numbers, int len) {
		// TODO Auto-generated method stub
		if (numbers==null||len<=0) {
			inputInvalid=true;
		}
		return inputInvalid;
	}

}

测试结果:


至于第二种解法以及深层次的扩展),请参考我的另一篇博客 寻找发帖水王的扩展

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值