题解 | #牛的体重统计#
牛的体重统计
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<>();
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 res = weightsA.length > 0 ? weightsA[0] : weightsB[0];
for (int key : map.keySet()) {
if (map.get(key) > map.get(res) ||
(map.get(key) == map.get(res) && key > res)) {
res = key;
}
}
return res;
}
}