题解 | #牛的体重统计#
牛的体重统计
https://www.nowcoder.com/practice/15276ab238c9418d852054673379e7bf
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param weightsA int整型一维数组 * @param weightsB int整型一维数组 * @return int整型 */ public int findMode (int[] weightsA, int[] weightsB) { // write code here //记录集合A,b中是数据 HashMap<Integer,Integer> map = new HashMap<>(); int res = 0; //初始数量 int count = 0; //遍历A中的数据, for(int i=0;i<weightsA.length;i++){ //将A中的数据存入map中 map.put(weightsA[i],map.getOrDefault(weightsA[i],0)+1); //如果数量大于大于count,则比较 if(map.get(weightsA[i]) >= count){ //当数量一定时,我们取最大的作为众数 if(map.get(weightsA[i]) == count){ res = Math.max(res,weightsA[i]); }else{ res = weightsA[i]; } count = map.get(weightsA[i]); } } //用同样的方法遍历B for(int i=0;i<weightsB.length;i++){ map.put(weightsB[i],map.getOrDefault(weightsB[i],0)+1); if(map.get(weightsB[i]) >= count){ if(map.get(weightsB[i]) == count){ res = Math.max(res,weightsB[i]); }else{ res = weightsB[i]; } count = map.get(weightsB[i]); } } return res; } }