面试题30

xiaoxiao2021-02-28  8

代码示例:

#include<iostream> #include<set> #include<iterator> #include<functional> #include <algorithm> using namespace std; typedef multiset<int, greater<int> > IntSet; typedef multiset<int, greater<int> >::iterator setIterator; void FindKSmall(int a[], int n, int k,IntSet&res) { if (a == NULL || n <= 0 || k > n||k<=0) return; res.clear(); int index; for (int index = 0; index < n; index++) { if (res.size() < k) { res.insert(a[index]); } else { setIterator it = res.begin(); if (a[index] < *it) { res.erase(it); res.insert(a[index]); } } } } int main() { const int n = 10; int k = 5; int a[n] = { 7, 3, 2, 6, 9, 0, 0, 10, 32, 5 }; cout << "原数组:"; for (int i = 0; i < n; i++) cout << a[i] << " "; cout << endl; IntSet res; cout << "最小的" << k << "个数:"; FindKSmall(a, n, k,res); for (setIterator it=res.begin(); it!=res.end(); it++) cout << *it << " "; cout << endl; }

转载请注明原文地址: https://www.6miu.com/read-750317.html

最新回复(0)