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;
}
相关推荐
X journey3 小时前
机器学习进阶(13):支持向量机SVM
算法·机器学习·支持向量机
洛水水4 小时前
【力扣100题】30.二叉树的直径
算法·leetcode·职场和发展
REDcker4 小时前
C++变量存储与ELF段布局详解 从const全局到rodata与nm_readelf验证实践
java·c++·面试
gihigo19984 小时前
Bezier曲线曲面生成算法
算法
刀法如飞5 小时前
Ontology本体论是什么数据结构?Palantir 技术原理介绍
数据结构·人工智能·ai编程·图论
平行侠5 小时前
024多精度大整数 - 突破硬件精度限制的任意精度运算
数据结构·算法
IronMurphy5 小时前
【算法四十五】139. 单词拆分
算法
王老师青少年编程6 小时前
csp信奥赛C++高频考点专项训练之字符串 --【字符串排序】:合并序列
c++·字符串·csp·高频考点·信奥赛·字符串排序·合并序列
洛水水6 小时前
【力扣100题】32.将有序数组转换为二叉搜索树
数据结构·算法·leetcode
handler017 小时前
UDP协议与网络通信知识点
c语言·网络·c++·笔记·网络协议·udp