题解 | #寻找大富翁#

寻找大富翁

https://www.nowcoder.com/practice/38131e23663746a992581d45f16e7a86

//C++版代码
#include <iostream>
#include <queue>
using namespace std;
int main() {
    int n, m;
    while (cin >> n >> m) {
        if (n == 0 && m == 0) break;
        priority_queue<int> pq;
        for (int i = 0; i < n; i++) {
            int temp;
            cin >> temp;
            pq.push(temp);
        }
        while (!pq.empty() && m--) {
            cout << pq.top() << " ";
            pq.pop();
        }
        cout << endl;
    }
    return 0;
}
//Java版代码
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextInt()) {
            int n = sc.nextInt();
            int m = sc.nextInt();
            if (n == 0 && m == 0) break;
            PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.comparingInt(a -> -a));
            while (n-- > 0) {
                pq.add(sc.nextInt());
            }
            while (!pq.isEmpty() && m-- > 0) {
                System.out.print(pq.poll() + " ");
            }
            System.out.println();
        }
    }
}
#Python版代码
from heapq import heapify, heappop
while True:
    try:
        n, m = map(int, input().split())
        if n == 0 and m == 0:
            break
        heap = list(map(lambda x: -int(x), input().split()))
        heapify(heap)
        while heap and m:
            print(-heappop(heap), end=" ")
            m -= 1
        print()
    except:
        break

全部评论

相关推荐

03-05 12:52
吉林大学 Java
挣K存W养DOG:他的价值在于把他家里积攒的财富回馈给社会
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务