题解 | #牛的体重统计#
牛的体重统计
https://www.nowcoder.com/practice/15276ab238c9418d852054673379e7bf
import java.util.*;
public class Solution {
public static int findMode (int[] weightsA, int[] weightsB) {
int m = weightsA.length;
int n = weightsB.length;
int[] res = new int[m + n];
System.arraycopy(weightsA,0,res,0,m);
System.arraycopy(weightsB,0,res,m,n);//多了一步变成一个数组,也可以不变
HashMap<Integer,Integer> map=new HashMap<>();
for (int i=0;i< res.length;i++){
map.put(res[i], map.getOrDefault(res[i],0)+1);//统计出现过的次数
}
int maxV=0,maxK=0;
for(Map.Entry<Integer,Integer> entry:map.entrySet()){//利用hashmap的特性,求出最大的key和vaule
if (entry.getValue()>maxV||(entry.getValue()==maxV&&entry.getKey()>maxK)){
maxV= entry.getValue();
maxK= entry.getKey();
}
}
return maxK;
}
}
