您的位置:首页 > 其它

腾讯2016测试开发岗笔试题--数组中出现次数超过一半的数字

2015-09-07 20:53 417 查看
题目:春节期间小明使用微信收到很多个红包,非常开心。在查看领取红包记录时发现,某个红包金额出现的次数超过了红包总数的一半。请帮小明找到该红包金额。写出具体算法思路和代码实现,要求算法尽可能高效。

思路:这题其实就是剑指offer上的第29题,书上给了两种思路,一个是排序后的中位数,一个是利用规律,即它出现的次数比其他所有数字出现的次数的和还要多。

package org.algorithm.pointoffer;

public class Item29 {

	public static int MoreThanHalfNum(int[] num, int length) {
		if(num.length <= 0 || num == null) 
			return -1;
		int result = num[0];
		int time = 1;
		for(int i = 1; i < length; i++) {
			if(time == 0) {
				result = num[i];
				time = 1;
			}	
			else if(result == num[i])
				time ++;
			else
				time --;
		}
		time = 0;
		for(int i = 0; i < length; i++)
			if(num[i] == result)
				time ++;
		if(time*2 > length)
			return result;
		else
			return -1;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int testArray[] = { 1, 2, 3, 2, 2, 2, 5, 4, 2 };  
		System.out.println(MoreThanHalfNum(testArray, 9));
	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: