[LeetCode]229. 求众数 II

众数

Posted by JinFei on November 12, 2021

题目描述

给定一个大小为 n 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。

Example1:

输入:[3,2,3] 输出:[3]

Example2:

输入:nums = [1] 输出:[1]

Example3:

输入:[1,1,1,3,3,2,2,2] 输出:[1,2]

Note:

  • 1 <= nums.length <= 5 * 10^4
  • -10^9 <= nums[i] <= 10^9

解题思路

class Solution {
public:
    static bool cmp(pair<int, int>& a, pair<int, int>& b){
        return a.second > b.second;
    }
    vector<int> majorityElement(vector<int>& nums) {
        vector<int> res;
        unordered_map<int, int> mmap;
        for(auto& i : nums){
            mmap[i]++;
        }
        for (auto & v : mmap) {
            if (v.second > nums.size() / 3) {
                res.push_back(v.first);
            }
        }
        return res;
    }
};