Java实现 找出数组中出现次数超过数组长度一半的元素

简述 :

给定一个数组,找出数组中元素出现次数超过数组长度一半的元素

如数组:

[4, 3, 2, 1, 1, 1, 1, 1, 1, 0 ]

其中超过一半的元素就是 1


两种实现的 算法描述:

1) 用快排中的Partition,分割数组直到找到pos等于数组正当中的那个元素,返回那个索引的值

2) 可以考虑成,结果的那个值对抗不等于结果的那个值,两方面打擂台,最后谁还留在台上,谁就是最后的解


代码:

package offer;

/**
 * In one array, there may be one element, its occurrence is more 
 * than half of the array size, so use these two methods to get  
 * the OccurrenceMoreThanHalf number
 */
public class OccurrenceMoreThanHalf {
	
	public static void main(String[] args) {
		int array[] = new int[10];
		for(Integer i = 0; i < 5; i++)
			array[i] = 4 - i;
		for(Integer i = 0; i < 5; i++)
			array[i + 4] = 1;
		System.out.print("Raw Array Data: [");
		for(Integer i : array){
			System.out.print(i + ", ");
		}
		System.out.println("]");
		
		System.out.println("Get Number Through Method_1: " 
				+ getNumMethod_1(array));
		System.out.println("Get Number Through Method_2: " 
				+ getNumMethod_2(array));
	}
	
	public static int getNumMethod_1(int array[]){
		int middle = array.length >> 1;
		int start = 0;
		int end = array.length - 1;
		int pos = Partition(array, start, end);
		while(pos != middle){
			if(pos < middle){
				start = pos + 1;
				pos = Partition(array, start, end);
			}
			else{
				end = pos - 1;
				pos = Partition(array, start, end);
			}
		}
		return array[pos];
	}
	
	public static int Partition(int array[], int start, int end){
		int baseValue = array[start];
		int basePos = start;
		for(int i = start + 1; i <= end; i++){
			if(array[i] < baseValue){
				basePos++;
				Swap(array, i , basePos);
			}
		}
		Swap(array, start, basePos);
		return basePos;
	}
	
	public static void Swap(int array[], int pos1, int pos2){
		int temp = array[pos1];
		array[pos1] = array[pos2];
		array[pos2] = temp;
	}
	
	public static int getNumMethod_2(int array[]){
		if(array.length == 0)
			throw new IllegalArgumentException();
		int resultNum = array[0];
		int occurrence = 0;
		for(int i = 0; i < array.length; i++){
			if(array[i] == resultNum)
				occurrence++;
			else{
				if(--occurrence == 0)
					resultNum = array[i];
			}
		}
		return resultNum;
	}
}

输出:



评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值