2016校招腾讯研发岗笔试题(第四题)

来源:互联网 发布:nginx tcp 转发原始ip 编辑:程序博客网 时间:2024/05/22 12:30

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

Java代码如下所示:

package tengxun;/** * 4. 春节期间小明使用微信收到很多个红包,非常开心。在查看领取红包记录时发现, * 某个红包金额出现的次数超过了红包总数的一半。请帮小明找到该红包金额。 * 写出具体算法思路和代码实现,要求算法尽可能高效 */public class Test04Money {public static int getMiddle(int[] source,int low,int high){int tep=source[low];//数组中的第一个作为中轴,即比较的基数while(low<high){while(low<high&&source[high]>=tep){high--;}source[low]=source[high];//比中轴小的记录移到低端while(low<high&&source[high]<tep){low++;}source[high]=source[low];//比中轴大的记录移到高端}source[low]=tep;//中轴记录到尾return low;//返回中轴的位置}public static void quickSort(int[] source,int low,int high){if(low<high){int middle=getMiddle(source, low, high);//将source数组一分为二quickSort(source, low, middle-1);//递归quickSort(source, middle+1, high);//递归}}public static int findMostMoney(int[] money){quickSort(money, 0, money.length-1);return money[((money.length-1)/2)];}public static void main(String[] args) {int[] money={1,3,4,2,3,2,2,5,9,8,2,2,2,2,2,2,2};int mostmoney=findMostMoney(money);System.out.println(mostmoney);}}


1 0
原创粉丝点击