To minimize the number of unique integers after removing exactly k elements, we should remove the integers with the lowest frequencies first. This way, we can eliminate more unique numbers with fewer removals.
classSolution {
public:int findLeastNumOfUniqueInts(vector<int>& arr, int k) {
unordered_map<int, int> freq;
for (int x : arr) freq[x]++;
vector<int> counts;
for (auto& p : freq) counts.push_back(p.second);
sort(counts.begin(), counts.end());
int ans = counts.size();
for (int c : counts) {
if (k >= c) { k -= c; ans--; }
elsebreak;
}
return ans;
}
};
classSolution {
publicintfindLeastNumOfUniqueInts(int[] arr, int k) {
Map<Integer, Integer> freq =new HashMap<>();
for (int x : arr) freq.put(x, freq.getOrDefault(x, 0) + 1);
List<Integer> counts =new ArrayList<>(freq.values());
Collections.sort(counts);
int ans = counts.size();
for (int c : counts) {
if (k >= c) { k -= c; ans--; }
elsebreak;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funfindLeastNumOfUniqueInts(arr: IntArray, k: Int): Int {
val freq = arr.groupingBy { it }.eachCount()
val counts = freq.values.sorted()
var ans = counts.size
var rem = k
for (c in counts) {
if (rem >= c) { rem -= c; ans-- } elsebreak }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
deffindLeastNumOfUniqueInts(self, arr: list[int], k: int) -> int:
from collections import Counter
freq = Counter(arr)
counts = sorted(freq.values())
ans = len(counts)
for c in counts:
if k >= c:
k -= c
ans -=1else:
breakreturn ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnfind_least_num_of_unique_ints(arr: Vec<i32>, k: i32) -> i32 {
use std::collections::HashMap;
letmut freq = HashMap::new();
for x in arr { *freq.entry(x).or_insert(0) +=1; }
letmut counts: Vec<_>= freq.values().cloned().collect();
counts.sort();
letmut ans = counts.len() asi32;
letmut k = k;
for c in counts {
if k >= c { k -= c; ans -=1; } else { break; }
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
findLeastNumOfUniqueInts(arr: number[], k: number):number {
constfreq=newMap<number, number>();
for (constxofarr) freq.set(x, (freq.get(x) ??0) +1);
constcounts= Array.from(freq.values()).sort((a, b) =>a-b);
letans=counts.length;
for (constcofcounts) {
if (k>=c) { k-=c; ans--; } elsebreak;
}
returnans;
}
}