跳到正文

题解

map排序

songyihao约 1 分钟
原文
文章信息与版本

文章信息

发布
2026年11月25日
收录
2026年11月29日
更新
2026年11月29日
篇幅
约 1 分钟
获赞
1
题目
P1177

版本

  1. v1当前

一种以map为容器,红黑树为底层逻辑的高效排序

时间复杂度: O(nlogn)O(n log n)
空间复杂度: O(n)O(n)

先看代码:

C++
#include<bits/stdc++.h>
using namespace std;
int n;
map<int,int> t;
int main(){	
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	cin>>n;
	while(n--){
		int x;
		cin>>x;
		t[x]++;
	}
	for(auto p:t)
		while(p.second--)
			cout<<p.first<<' ';
	return 0;
}

例如序列 5,4,3,5,4,2,1,在map中存为:

键值
11
21
31
42
52

按值输出键即可

缺点:常数较大,时间复杂度和空间复杂度明显低于sort排序与归并排序、快速排序

优点:比较高效,巧用map容器的自动插入、默认初始值的性质,结合计数排序思路,避免值域内无效访问,得到大幅的提升。

原文