题解 | #牛的体重统计#
牛的体重统计
https://www.nowcoder.com/practice/15276ab238c9418d852054673379e7bf
考察哈希表的用法
做法是,先合并数组并统计个数汇总到哈希表中,哈希表的键值对为体重:次数。
在接下来的判断中需要比对次数和体重的值,同时根据题意,次数一样的时候取最大的体重。最后将结果返回即可。
Java代码如下所示
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param weightsA int整型一维数组 * @param weightsB int整型一维数组 * @return int整型 */ public int findMode (int[] weightsA, int[] weightsB) { // write code here HashMap<Integer,Integer> map = new HashMap<>(); //体重:次数 int count = -1; int res = -1; //标记众数的值 for(int num:weightsA){ if(map.containsKey(num)){ map.put(num,map.get(num)+1); }else{ map.put(num,1); } } for(int num:weightsB){ if(map.containsKey(num)){ map.put(num,map.get(num)+1); }else{ map.put(num,1); } } for(Object o : map.keySet()){ if(count<=map.get(o)&&res<(Integer)o){ //注意次数一致的时候取更大的体重 count = map.get(o); res = (Integer)o; } } return res; } }