题解 | #牛的体重统计#
牛的体重统计
https://www.nowcoder.com/practice/15276ab238c9418d852054673379e7bf
- 题目考察的知识点 : 哈希表使用
- 题目解答方法的文字分析 :
简单来说,首先定义一个空字典 cnt 来记录每个体重出现的次数。然后遍历两个体重数组 weightsA 和 weightsB,将每个体重出现的次数加入到 cnt 中。遍历完毕后,再遍历整个字典 cnt,找到出现次数最多、值最大的那一个体重,并返回它。
- 本题解析所用的编程语言 : Python3
- 完整且正确的编程代码:
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param weightsA int整型一维数组 # @param weightsB int整型一维数组 # @return int整型 # class Solution: def findMode(self , weightsA: List[int], weightsB: List[int]) -> int: cnt = {} for weight in weightsA: cnt[weight] = cnt.get(weight, 0) + 1 for weight in weightsB: cnt[weight] = cnt.get(weight, 0) + 1 ans, aans = -1, 0 for weight, count in cnt.items(): if count >= ans: if weight > aans: ans, aans = count, weight return aans
牛客高频top202题解系列 文章被收录于专栏
记录刷牛客高频202题的解法思路