1481. Least Number of Unique Integers after K Removals
HashMap + Sort
T: O(n + mlogm + k), n is arr length. m is the number of key in hashmap
S: O(n + m)```java
class Solution {
public int findLeastNumOfUniqueInts(int[] arr, int k) {
Map<Integer, Integer> freq = new HashMap<>();
for (int num : arr) {
freq.put(num, freq.getOrDefault(num, 0)+1);
}
List<Integer> list = new ArrayList<>(freq.keySet());
Collections.sort(list, (a, b) -> freq.get(a) - freq.get(b));
for (int i = 0; i < list.size() && k > 0; i++) {
int key = list.get(i);
int count = freq.get(key);
while (count > 0) {
count--;
if (count == 0) {
freq.remove(key);
}
k--;
if (k == 0) {
return freq.size();
}
}
}
return freq.size();
}
}
/**
T: O(n + mlogm + k), n is arr length. m is the number of key in hashmap
S: O(n + m)
*/
```HashMap + bucket sort
because freq at most is arr.length... so we can create a bucket array to sort the count
Last updated
Was this helpful?