题解 | #牛的体重统计#
牛的体重统计
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;
}
}
#题解#
查看23道真题和解析