题解 | #输入n个整数,输出其中最小的k个#
输入n个整数,输出其中最小的k个
https://www.nowcoder.com/practice/69ef2267aafd4d52b250a272fd27052c
#include <bits/stdc++.h> #include <functional> using namespace std; void heapify(vector<int> &heap, int i, int heapSize){ int last = i; int l = 2 * i + 1; int r = 2 * i + 2; if(l < heapSize && heap[l] < heap[last]){ last = l; } if(r < heapSize && heap[r] < heap[last]){ last = r; } if(i != last){ swap(heap[i], heap[last]); heapify(heap, last, heapSize); } } void buildHeap(vector<int>& heap, int heapSize){ for(int i = heapSize / 2 - 1; i >= 0; --i){ heapify(heap, i, heapSize); } // for(int i = heapSize - 1; i >= 0; --i){ // swap(heap[0], heap[i]); // heapify(heap, 0, i); // } } int main() { int n, k; cin >> n >> k; int x; // auto cmp = ([](const int a, const int b) { // return a > b; // }); // priority_queue<int, vector<int>, decltype(cmp)> q(cmp); // while (cin >> x) { // q.push(x); // } //vector<int> res; // while(k--){ // res.push_back(q.top()); // q.pop(); // } // for(auto &i : res){ // cout << i << " "; // } vector<int> heap; while(cin >> x){ heap.push_back(x); } buildHeap(heap, n); int heapSize = n; for(int i = 0; i < k; ++i){ cout << heap[0] << " "; swap(heap[0], heap[heapSize - 1]); heapSize--; heapify(heap, 0, heapSize); } return 0; } // 64 位输出请用 printf("%lld")