[LeetCode] Least Number of Unique Integers after K Removals

1481. Least Number of Unique Integers after K Removals

Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int findLeastNumOfUniqueInts(vector<int>& arr, int k) {
unordered_map<int, int> m;
vector<int> heap;
for(auto& a : arr) ++m[a];
transform(m.begin(), m.end(), std::back_inserter(heap), [](const pair<int, int> &p) { return p.second; } );
make_heap(begin(heap), end(heap), greater<int>());
while(k > 0) {
k -= heap.front();
pop_heap(begin(heap), end(heap), greater<int>());
heap.pop_back();
}
return k & (~k + 1) ? heap.size() + 1: heap.size();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/13/PS/LeetCode/least-number-of-unique-integers-after-k-removals/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.