838. 堆排序,

完全二叉树手写小根堆

堆排序的五大功能

1.插入一个数

2.求集合当中的最小值

3.删除最小值

4.删除任意一个元素

5.修改任意一个元素

最后两个功能stl中的堆即优先队列都没法直接实现

输入一个长度为 n 的整数数列,从小到大输出前 m 小的数。

输入格式

第一行包含整数 n 和 m。

第二行包含 n 个整数,表示整数数列。

输出格式

共一行,包含 m 个整数,表示整数数列中前 m 小的数。

数据范围

1≤m≤n≤105,

1≤数列中元素≤109

输入样例:
复制代码
5 3
4 5 1 3 2
输出样例:
复制代码
1 2 3

解析:

此代码的第一次排序时间复杂的为 O(n)

cpp 复制代码
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>

using namespace std;
typedef long long LL;
const int N = 1e5 + 5, M = 3e5 + 5;
int n, m;
int h[N],cnt;

void down(int u) {
	int t = u;
	if (u * 2 <= cnt && h[2 * u] < h[t])t = 2 * u;
	if (2 * u + 1 <= cnt && h[2 * u + 1] < h[t])t = 2 * u + 1;
	if (u != t) {
		swap(h[t], h[u]);
		down(t);
	}
}

int main() {
	cin >> n >> m;
	for (int i = 1; i <= n; i++)scanf("%d", &h[i]);
	cnt = n;
	for (int i = n / 2; i; i--)down(i);//时间复杂度为 O(n)
	
	while (m--) {
		printf("%d ", h[1]);
		h[1] = h[cnt];
		cnt--;
		down(1);
	}
	return 0;
}
相关推荐
海清河晏111几秒前
数据结构 | 二叉平衡搜索树
开发语言·数据结构·visual studio
鱼儿也有烦恼4 分钟前
数据结构合集
算法·algorithm
KouFiee17 分钟前
同名隐藏基础
开发语言·c++
兰令水27 分钟前
hot100【acm版】【2026.7.11/12打卡-java版本】
java·开发语言·数据结构·算法·职场和发展
研來如此35 分钟前
图像文件大小
人工智能·算法·计算机视觉
千纸鹤安安36 分钟前
开源 Agent 框架实战:用自然语言替代 Crontab 做运维
算法
从零开始的代码生活_37 分钟前
C++ string 详解:常用接口、字符串算法与深拷贝实现
开发语言·c++·后端·学习·算法
Keven_1143 分钟前
算法札记:差分约束系统为啥叫差分约束系统Σ(っ °Д °;)っ
算法·差分约束系统
XWalnut1 小时前
LeetCode刷题 day29
java·算法·leetcode
embrace_the_sunhaha1 小时前
卡尔曼滤波理解
算法