题解 | #查找第K小数#
查找第K小数
http://www.nowcoder.com/practice/204dfa6fcbc8478f993d23f693189ffd
需要将去重复考虑进去
#include <iostream>
#include <queue>
#include <set>
using namespace std;
int main()
{
int N;
while (cin >> N) {
priority_queue<int> pq;
vector<int> vec;
set<int> st;
while (N--) {
int val;
cin >> val;
vec.push_back(val);
}
int k;
cin >> k;
for (int i = 0; i < vec.size(); i++) {
if (pq.size() < k) {
if (st.find(vec[i]) != st.end()) {
continue;
}
st.insert(vec[i]);
pq.push(vec[i]);
}
else if (pq.size() == k) {
int tmp = pq.top();
if (vec[i] >= tmp) {
continue;
}
else {
if (st.find(vec[i]) != st.end()) {
continue;
}
st.erase(pq.top());
pq.pop();
st.insert(vec[i]);
pq.push(vec[i]);
}
}
}
cout << pq.top() << endl;
}
return 0;
}