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