题解 | #牛的体重统计#
牛的体重统计
https://www.nowcoder.com/practice/15276ab238c9418d852054673379e7bf
知识点:哈希表
遍历两个数组,使用getOrDefault方法,将元素和出现次数存入HashMap中,若不存在,则次数为1,若存在,则将出现次数+1,使用Entry来遍历HashMap,获得出现次数最多且元素值最大的元素,即为答案。
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 Map<Integer, Integer> map = new HashMap<>(); for(int i: weightsA) { map.put(i, map.getOrDefault(i, 0) + 1); } for(int i: weightsB) { map.put(i, map.getOrDefault(i, 0) + 1); } int num = 0, count = 0; for(Map.Entry<Integer, Integer> entry: map.entrySet()) { if(entry.getValue() > count || entry.getValue() == count && entry.getKey() > num) { num = entry.getKey(); count = entry.getValue(); } } return num; } }