腾讯微信红包
春节期间小明使用微信收到很多个红包,非常开心。在查看领取红包记录时发现,某个红包金额出现的次数超过了红包总数的一半。请帮小明找到该红包金额。写出具体算法思路和代码实现,要求算法尽可能高效。
给定一个红包的金额数组gifts及它的大小n,请返回所求红包的金额。
若没有金额超过总数的一半,返回0。
[1,2,3,2,2],5
返回:2
代码:
import java.util.*;
public class GrayCode {
public int getValue(int[] gifts, int n) {
int getValue=0;
int[]arr=new int[n];
Arrays.sort(gifts);
int count0=1;
int count=1;
for(int i=0;i<gifts.length-1;i++){
if(gifts[i]==gifts[i+1])
count++;
else
if(count>count0){
count0=count;
count=1;
getValue=gifts[i];
}
else count=1;
}
if(count0>n/2){
return getValue;
}
else
return 0;
}
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
while(sc.hasNextInt()){
int n=sc.nextInt();
int[] gifts=new int[n];
for(int i=0;i<n;i++){
gifts[i]=sc.nextInt();
}
GrayCode t=new GrayCode();
System.out.println(t.getValue(gifts,n));
}
}
}
收获:(1)先进行排序,再统计出现次数最多的数字,记录数字和那个数。