
Sponsored
Sponsored
This approach involves two main steps. First, count the frequency of each integer in the array. Second, use a min-heap (or priority queue) to remove the integers with the smallest frequency first. This approach ensures that we are removing the least frequent integers to reach the least number of unique integers efficiently.
Time Complexity: O(n log n) due to sorting the frequency array. Space Complexity: O(n) for storing the frequency counts.
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5class Solution {
6 public int LeastNumberOfUniqueInts(int[] arr, int k) {
7 var freqMap = new Dictionary<int, int>();
8 foreach (var num in arr) {
9 if (freqMap.ContainsKey(num))
10 freqMap[num]++;
11 else
12 freqMap[num] = 1;
13 }
14
15 var frequencies = freqMap.Values.ToList();
16 frequencies.Sort();
17
18 int uniqueCount = frequencies.Count;
19 foreach (var freq in frequencies) {
20 if (k >= freq) {
21 k -= freq;
22 uniqueCount--;
23 } else {
24 break;
25 }
26 }
27
28 return uniqueCount;
29 }
30
31 static void Main(string[] args) {
32 int[] arr = {4, 3, 1, 1, 3, 3, 2};
33 int k = 3;
34 Solution s = new Solution();
35 Console.WriteLine(s.LeastNumberOfUniqueInts(arr, k));
36 }
37}This C# solution uses a Dictionary to record the frequency of each element. The frequencies are sorted and used to determine the removals, effectively decrementing the count of unique integers.
This approach takes a greedy strategy to count frequencies of integers and sorts them. By progressively removing elements with smallest frequencies, it directly calculates the least number of unique integers remaining after exactly k removals.
Time Complexity: O(n log n) due to the qsort on frequencies. Space Complexity: O(n) for arrays used in frequency counting.
using System.Collections.Generic;
using System.Linq;
public class Solution {
public int LeastNumberOfUniqueInts(int[] arr, int k) {
Dictionary<int, int> count = new Dictionary<int, int>();
foreach (int num in arr) {
if (count.ContainsKey(num))
count[num]++;
else
count[num] = 1;
}
List<int> frequencies = count.Values.ToList();
frequencies.Sort();
int uniqueCount = frequencies.Count;
foreach (int f in frequencies) {
if (k >= f) {
k -= f;
uniqueCount--;
} else {
break;
}
}
return uniqueCount;
}
public static void Main(string[] args) {
Solution sol = new Solution();
Console.WriteLine(sol.LeastNumberOfUniqueInts(new int[] {5, 5, 4}, 1));
}
}This C# code uses a dictionary to determine the frequency of each element. Frequencies are sorted, allowing for strategic removal to reduce the count of unique integers remaining.