目录

  • 饭后小甜点leetcode——堆
    • 堆的基础实现
    • 703. Kth Largest Element in a Stream
    • 295. Find Median from Data Stream
    • 239. Sliding Window Maximum

饭后小甜点leetcode——堆

堆的基础实现

MaxHeap.cs

MinHeap.cs

IndexMinHeap.cs

703. Kth Largest Element in a Stream

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.

Example:

int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10); // returns 5
kthLargest.add(9); // returns 8
kthLargest.add(4); // returns 8

思路:
用优先队列,但要定义为小顶堆那种弹出规则。先入队,如果优先队列中总元素个数超过了k,那么就弹出,使得top始终为第k大的值。

代码(C++):

class KthLargest {public:priority_queue<int, vector<int>, greater<int>> pq;// 使用优先队列需要 #include<queue>
class KthLargest {public:    priority_queue<int, vector<int>, greater<int>> pq;// 使用优先队列需要 #include<queue>// 默认情况下不需要写后两个参数,默认为大顶堆,优先弹出最大的,此时我们需要优先弹出最小的,于是加上后两个参数,虽然第三个参数看上去像是弹出较大的。。。但并不是这样的,注意下下// 当自己在IDE里写的时候,可能 greater会报错,说 greater不是模板,这时候只要 #include<functional>即可int size;// 记录k值// 构造函数KthLargest(int k, vector<int> nums) {size = k;for (int i = 0;i < nums.size();i++) {pq.push(nums[i]);if (pq.size() > k) {pq.pop();}}}int add(int val) {pq.push(val);if (pq.size() > size) {pq.pop();}return pq.top();}
};
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/

295. Find Median from Data Stream

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.

For example,
[2,3,4], the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.

Example:

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2

思路
该题要求寻找数据流中的中位数,首先得明白什么是中位数,中位数即一组排好序的数中最中间那一个儿数,如果该组数是偶数个数,中位数就是最中间两个的平均值。这样一来我们可以把这组数分成两堆,一个大顶堆放较小的那一拨儿数字,一个小顶堆放较大的那一拨儿数字,这样的话从堆顶就可以得到中位数。那么难点就在于如何调整这两个堆,使得它们两刚好一个放较小的那拨儿数,一个放较大的那拨儿数。可以这样想,首先把新来的数放到较小数堆里一下,如果它成了大顶堆的顶点,说明它很可能应该放到较大数堆里,于是弹出堆顶;如果它没成大顶堆顶点,那说明它来对地方了,但是小数堆的个数变多了,为了平衡,得弹出一个最大的给大数堆,所以无论如何都得把小数堆堆顶弹出给大数堆。完了以后如果大数堆个数比小数堆多了,得把它最小的那个给小数堆。

代码(C++)

class MedianFinder {priority_queue<int> lo;                              // max heappriority_queue<int, vector<int>, greater<int>> hi;   // min heappublic:// Adds a number into the data structure.void addNum(int num){lo.push(num);                                    // Add to max heaphi.push(lo.top());                               // balancing steplo.pop();if (lo.size() < hi.size()) {                     // maintain size propertylo.push(hi.top());hi.pop();}}// Returns the median of current data streamdouble findMedian(){return lo.size() > hi.size() ? (double) lo.top() : (lo.top() + hi.top()) * 0.5;}
};

239. Sliding Window Maximum

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

Example:

Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:

Window position Max


[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
Note:
You may assume k is always valid, 1 ≤ k ≤ input array’s size for non-empty array.

思路1:
这题可以用堆试试,但做出来效率有点低,就是每移动一下窗口新建一个堆然后返回堆顶(基本把堆当成了自动排序工具。。)先上一下代码。
代码1(C++):

class Solution {public:vector<int> maxSlidingWindow(vector<int>& nums, int k) {vector<int> res;if (nums.empty()) {return res;}for (int i = 0;i <= nums.size()-k;i++) {priority_queue<int> pq;for (int j = i;j < i+k;j++) {pq.push(nums[j]);}res.push_back(pq.top());}return res;}
};

思路2:
这个题其实最好用双头队列,在deque中保存窗口在数组中对应的首尾下标,然后对于新来的数,从右到左看,只要比新来的小就pop,最后dq中剩下的数中最左边的应该是最大的,为啥不能从左往右删呢,因为如果这样的话,新来的数大小如果刚好处于中间的位置就不好判断了。

代码2(C++):

class Solution {public:vector<int> maxSlidingWindow(vector<int>& nums, int k) {vector<int> res;if (nums.empty()) {return res;}deque<int> dq;for (int i = 0;i < nums.size();i++) {if (!dq.empty() && dq.front() == i-k) {dq.pop_front();}while (!dq.empty() && nums[i] > nums[dq.back()]) {dq.pop_back();}dq.push_back(i);if (i >= k - 1) {res.push_back(nums[dq.front()]);}}return res;}
};

饭后小甜点leetcode——堆相关推荐

  1. 小甜点,RecyclerView 之 ItemDecoration 讲解及高级特性实践

    本篇文章已授权微信公众号 guolin_blog (郭霖)独家发布 毫无疑问,RecyclerView 是现在 Android 世界中最重要的系统组件之一,它的出现就是为了高效代替 ListView ...

  2. 不平等博弈问题学习记录(三)(对于超实数在博弈下左大右小以及多堆情况的扩充)

    前言 今天写的这一篇文章离写第一篇文章的时间可能有几天了,并且在这段时间里也有人向我提出了我错误的地方,现已做出更改 今天,我们又做到了一道题目,也是不平等博弈的,听了讲题,我对不平等博弈有了更深的理 ...

  3. 2016vijos 1-2 股神小L(堆)

    维护前i天的最优解,那么在后面可能会对前面几天的买卖情况进行调整 如果前面买入,买入的这个在后面一定不会卖出 如果前面卖出,卖出的这个可能会在后面变成买入,因为买这个,卖后面的会获得更多的收益 用一个 ...

  4. 算法给小码农堆魂器--铁血柔情

    文章目录 堆 堆的概念及结构 堆的性质 堆的结构(这里实现大堆) 堆的结构体 堆初始化函数HeapInit 堆销毁函数HeapDestroy 堆打印函数HeapPrint 向上调整函数AdjustUp ...

  5. 洛谷P2085ssl1411OJ1370-最小函数值【堆,贪心】

    前言 有一个东西卡了我一会 折叠N*或N+ 正整数集 (由全体正整数组成的集合) N*:={1,2,3,-,n,-} 题目 洛谷P2085 OJ1370 给出n个ai,bi,ci.定义一个函数 fi( ...

  6. 微信小程序实现堆叠式轮播

    1.实现效果 2.实现原理 1.css的var()函数 var() 函数用于插入自定义属性的值,而不是另一个属性的值的任何部分. 语法: var(custom-property-name, value ...

  7. 平平无奇的“小插座”,堆出千亿市值的公牛集团

    有些生意看起来不高大上,但赚钱能力却不含糊,例如农夫山泉创始人钟琰琰便是靠卖水成为了中国首富.而依靠插座这种我们司空见惯的家居和办公日常用品,公牛集团成为了国内名副其实的"插座一哥" ...

  8. 赫斌C语言全案文,自用笔记,给后来者一点思路

    1.CPU 内存条 硬盘 显卡 主板  显示器 之间的关系 比如在硬盘上的一部电影,CPU如果想调用它,就要把硬盘上的数据调用到内存条(CPu不能直接调用硬盘上的数据),CPU处理调用在内存条的数据, ...

  9. 读《CSS禅意花园》中学习到的

    昨晚看完了网上名气很大的<CSS禅意花园>,其实整本书的内容都只是从web设计人员的角度出发,这本书对于网页制作人员而言,可以这么形容它的价值:饭后小甜点.     这是一本小品式的书.一 ...

  10. 小顶堆数据结构C/C++代码实现

    相比队列和栈,很多人可能对堆的概念比较陌生,下面个给出堆的本质概念 一.堆也是一种数据结构,从实际应用意义来说,他是一种最优级别数据永远在第一位的队列,本文皆以最小值为例(小顶堆),即它变相是一种会永 ...

最新文章

  1. CentOS 终端显示中文异常解决办法
  2. Python的random
  3. Python中制作词云的WordCloud参数详解
  4. 解锁Android性能优化的五大误区!满满干货指导
  5. 怎样查阅电脑最大能够扩充多大的内存
  6. python多个对象嵌套会有问题吗_Python列表嵌套常见坑点及解决方案
  7. 二次bootloader关于boot28.asm应用的注意事项,28035的
  8. NOIP模拟题——复制粘贴2
  9. JZYZOJ1384 种花小游戏 状压dp
  10. 详解 Flutter engine多线程、Dart isolate和异步
  11. 使用R进行pubmed爬虫
  12. usb连接不上 艾德克斯电源_艾德克斯 ITECH电源RS232通讯设置简易教程
  13. 元宇宙发展研究报告2.0版本(清华大学)
  14. ARGB1555内部存储空间的大小与ARGB转换方式
  15. 各种题材的手游游戏代码素材推荐,不容错过
  16. 阿里云javaweb开发环境搭建(一)(jdk+Tomcat)
  17. A,NS,cname,forward,txt,aaaa记录讲解
  18. win2008集群文件服务器,Windows2008R2+MSCS集群配置.doc
  19. 最具影响力的十大扫地机器人品牌
  20. lgg6 android 9,【LGG6评测】18:9奇葩比例没采用骁龙835 LG G6解析(全文)_LG G6_手机评测-中关村在线...

热门文章

  1. Apache Kylin PMC 马洪宾:开源,就是一场“螺旋上升”的旅程
  2. 纯洁的心--佩雷尔曼
  3. U盘打不开的常见情况和解决方法
  4. 美国心脏协会:六种心血管疾病的症状区别
  5. EDP/DP转HDMI OUT 支持常用分辨率,最大支持4K@60Hz
  6. Mud Puddles ( bfs )
  7. delphi报表_顶级4 Delphi报表工具
  8. 解决DELL WIN7 bootmgr is missing
  9. 2020年最新PHP面试题汇总(附答案)
  10. 保龄球积分c语言程序,C语言保龄球积分.doc