


本质:找前k大值。
难点:如何下标递增返回ans?
解决方案:得到前k大值后,把出现的元素以及出现的个数放在hash中,然后遍历一遍数组,每次- -即可得到。
class Solution {
public:
vector<int> maxSubsequence(vector<int>& nums, int k) {
vector<int> ans;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
int n = nums.size();
unordered_map<int, int> val;
for (int i = 0; i < n; ++i) {
if (pq.size() < k) pq.push({nums[i], i});
else if (nums[i] > pq.top().first) {
pq.pop();
pq.push({nums[i], i});
}
}
while (!pq.empty()) {
val[pq.top().first]++;
pq.pop();
}
for (auto& each : nums) {
if (val.count(each) && val[each]) {
ans.push_back(each);
val[each]--; //出现过的--即可。
}
}
return ans;
}
};
