首页 > 其他分享 >LeetCode刷题记录.Day29

LeetCode刷题记录.Day29

时间:2022-11-30 22:44:53浏览次数:59  
标签:map Day29 int pri vector que 小顶 LeetCode 刷题

前 K 个高频元素

class Solution {
public:
    // 小顶堆
    class mycomparison {
    public:
        bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs) {
            return lhs.second > rhs.second;
        }
    };
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int>map;
        for(int i = 0; i < nums.size(); i++){
            map[nums[i]]++; //值做索引统计频率
        }
        // 定义一个小顶堆,大小为k
        priority_queue<pair<int, int>, vector<pair<int, int>>, mycomparison> pri_que;

        // 建立小顶堆
        for (unordered_map<int, int>::iterator it = map.begin(); it != map.end(); it++) {
            pri_que.push(*it);
            if (pri_que.size() > k) { // 如果堆的大小大于了K,则队列弹出,保证堆的大小一直为k
                pri_que.pop();
            }
        }

        // 找出前K个高频元素,因为小顶堆先弹出的是最小的,所以倒序来输出到数组
        vector<int> result(k);
        for (int i = k - 1; i >= 0; i--) {
            result[i] = pri_que.top().first;
            pri_que.pop();
        }
        return result;
    }
};

数据结构基础不好,堆的思想,怎么使用,二叉树,都需要补补,此题也仅仅是照猫画虎背下来了 之后回过头来要继续研究

标签:map,Day29,int,pri,vector,que,小顶,LeetCode,刷题
From: https://www.cnblogs.com/tianmaster/p/16940028.html

相关文章

  • leetcode-160-easy
    IntersectionofTwoLinkedListsGiventheheadsoftwosinglylinked-listsheadAandheadB,returnthenodeatwhichthetwolistsintersect.Ifthetwolinke......
  • leetcode-111-easy
    MinimumDepthofBinaryTreeGivenabinarytree,finditsminimumdepth.Theminimumdepthisthenumberofnodesalongtheshortestpathfromtherootnode......
  • 力扣 leetcode 162. 寻找峰值
    问题描述峰值元素是指其值严格大于左右相邻值的元素。给你一个整数数组nums,找到峰值元素并返回其索引。数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即......
  • 力扣 leetcode 153. 寻找旋转排序数组中的最小值
    问题描述已知一个长度为n的数组,预先按照升序排列,经由1到n次旋转后,得到输入数组。例如,原数组nums=[0,1,2,4,5,6,7]在变化后可能得到:若旋转4次,则可以得到[4......
  • 力扣 leetcode 33. 搜索旋转排序数组
    问题描述整数数组nums按升序排列,数组中的值互不相同。在传递给函数之前,nums在预先未知的某个下标k(0<=k<nums.length)上进行了旋转,使数组变为[nums[k],nums[k......
  • 力扣 leetcode 895. 最大频率栈
    问题描述设计一个类似堆栈的数据结构,将元素推入堆栈,并从堆栈中弹出出现频率最高的元素。实现FreqStack类:FreqStack()构造一个空的堆栈。voidpush(intval)将一......
  • 力扣刷题心得
    二叉树篇今天是2022年11月30日,本以为疫情在11月会结束,没想到又继续封控了一个月,10月已经封了半个月,那时候就打算11月的时候,坚持每天力扣,幸不辱命。这个月也是跟着代码随......
  • [LeetCode] 1207. Unique Number of Occurrences
    Givenanarrayofintegers arr,return true ifthenumberofoccurrencesofeachvalueinthearrayis unique,or false otherwise.Example1:Input:arr......
  • #yyds干货盘点# LeetCode程序员面试金典:URL化
    题目:URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以......
  • 【算法训练营day21】LeetCode530.二叉搜索树的最小绝对差 LeetCode501. 二叉搜索树中
    LeetCode530.二叉搜索树的最小绝对差题目链接:530.二叉搜索树的最小绝对差初次尝试利用二叉搜索树的性质:中序遍历的结果是有序递增数组,最后遍历该数组得到最小绝对差。c......