[LeetCode] Reduce Array Size to The Half

1338. Reduce Array Size to The Half

You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.

Return the minimum size of the set so that at least half of the integers of the array are removed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int minSetSize(vector<int>& arr) {
unordered_map<int, int> freq;
for(auto& a : arr) freq[a]++;
int n = arr.size(), rm = 0, res = 0;
priority_queue<int> q;
for(auto& [_, f] : freq) q.push(f);
while(!q.empty() and rm * 2 < n) {
rm += q.top(); q.pop();
res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/08/PS/LeetCode/reduce-array-size-to-the-half/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.