题解 | #牛的体重统计#

牛的体重统计

https://www.nowcoder.com/practice/15276ab238c9418d852054673379e7bf

知识点

哈希表

思路说明

利用哈希表统计不同体重的牛的个数; 遍历哈希表找到众数

时间复杂度

遍历一遍数组的时间复杂度为O(n)

unordered_map插入的时间复杂度为O(n)

遍历哈希表的时间复杂度为O(n)

综合时间复杂度为O(n)

AC code (C++)

#include <unordered_map>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param weightsA int整型vector 
     * @param weightsB int整型vector 
     * @return int整型
     */
    int findMode(vector<int>& weightsA, vector<int>& weightsB) {
        // write code here
        unordered_map<int, int> cnt;
        for (auto x : weightsA) cnt[x] += 1;
        for (auto x : weightsB) cnt[x] += 1;
        int res = -1, mx = -1;
        for (auto [k, v] : cnt) {
            if (v > mx or (v == mx and k > res)) {
                mx = v;
                res = k;
            }
        }
        return res;
    }
};

全部评论

相关推荐

09-14 17:23
门头沟学院
故事和酒66:所以说副业很重要,程序员干到40岁,再怎么也赚300万了,吃吃利息也够活下去
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务