输出前k大的数

GitHub跳转原题关系图返回列表

题目描述

给定长度为 nn(n<105n<10^5)的整数数组和 k<nk<n,把前 kk 大的数从大到小逐行输出,元素可正可负、可重复;输入:第一行 nn,第二行 nn 个整数(绝对值 ≤108\le 10^8),第三行 kk。 样例:

text
10 4 5 6 9 8 7 1 2 3 0 5
→ 9 8 7 6 5

思路

用 std::sort 配 greater<ll>() 把数组排成降序,再取前 kk 项逐行输出即可。

参考代码

Python 版:

python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-30 01:07
# update_at: 2026-09-30 01:07

import sys


def solve() -> None:
    data = iter(map(int, sys.stdin.buffer.read().split()))
    n = next(data)                                     # 数组长度,只用来读走 n 个数
    nums = [next(data) for _ in range(n)]
    k = next(data)                                     # 要输出的最大数个数

    # 前 k 大 = 降序排列的前 k 个;无需为 k 的大小分情况,切片天然保留重复元素
    print('\n'.join(map(str, sorted(nums, reverse=True)[:k])))


if __name__ == "__main__":
    solve()

C++ 版(同一算法):

cpp
/**
 * Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
 * rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
 * rainboy的学习导航网站: https://idx.roj.ac.cn
 * create_at: 2026-10-05 06:12
 * update_at: 2026-10-05 06:12
 */
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

const int MAXN = 100005;

// a[i]:第 i 个数组元素;值域是 ±1e9,用 ll 保存。
ll a[MAXN];

ll n; // 数组长度
ll k; // 要输出的最大数个数

void read_input() {
    // 按 token 流读入,容忍前导空行与任意空白分隔(也能处理负数)。
    string buf;
    vector<ll> tok;
    while (cin >> buf) {
        tok.push_back(atoll(buf.c_str()));
    }
    n = tok[0];
    for (ll i = 1; i <= n; i++) {
        a[i] = tok[i];
    }
    k = tok[n + 1];
}

void solve() {
    // 前 k 大 = 降序排序后的前 k 项,sort 默认升序,再用 greater<ll>() 翻成降序。
    sort(a + 1, a + n + 1, greater<ll>());
    // 逐行输出前 k 项
    for (ll i = 1; i <= k; i++) {
        cout << a[i] << "\n";
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    read_input();
    solve();

    return 0;
}