0
点赞
收藏
分享

微信扫一扫

Leetcode 347. 前 K 个高频元素(牛,终于解决)

月孛星君 2022-04-13 阅读 58
c++

在这里插入图片描述

给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。

示例 1:

输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]

示例 2:

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

提示:

  • 1 <= nums.length <= 10^5
  • k 的取值范围是 [1, 数组中不相同的元素的个数]
  • 题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的

Code:

class Solution {
public:
    
    typedef pair<int,int> PAIR;
    struct CmpByValue {
        bool operator()(const PAIR& lhs, const PAIR& rhs) {
            return lhs.second > rhs.second;
        }
    };
    vector<int> topKFrequent(vector<int>& nums, int k) {
        map<int,int>mymap;
        for(int i=0;i<(int)nums.size();i++)
        {

            int temp=nums[i];
            mymap.insert(pair<int,int>(nums[i],count(nums.begin(),nums.end(),nums[i])));
            //这一步是删除当前所有元素,减少时间复杂度,否则案例过不了
            nums.erase(std::remove(nums.begin(), nums.end(),temp), nums.end());
            i=-1;

        }
        //把map中元素转存到vector中
        vector<PAIR> map_vec(mymap.begin(), mymap.end());
        //对vector排序
        sort(map_vec.begin(), map_vec.end(), CmpByValue());
        vector<int>res;
        for(int i=0;i<k;i++)
        {
            res.push_back(map_vec[i].first);
        }
        return res;   
    }
};
举报

相关推荐

0 条评论