题解 | #牛的体重统计#
牛的体重统计
https://www.nowcoder.com/practice/15276ab238c9418d852054673379e7bf
知识点
哈希
解题思路
将两个数组出现的数的次数存到哈希表中,key:数,val次数。
遍历整个哈希表,ans存放最终的数,max存放最多出现的次数,如果当前的val大于max或者当前的val等于val并且key大于ans(因为如果val相同取最大的key)则更新ans和max。
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 num : weightsA) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
for (int num : weightsB) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
int ans = 0;
int max = 0;
for (Map.Entry<Integer, Integer> integerEntry : map.entrySet()) {
if(integerEntry.getValue() > max || (integerEntry.getKey() > ans && integerEntry.getValue() == max)){
max = integerEntry.getValue();
ans = integerEntry.getKey();
}
}
return ans;
}
}
查看6道真题和解析