classSolution { public: intminSetSize(vector<int>& arr){ unordered_map<int, int> ma; for (int t : arr) { ma[t]++; } vector<int> times; for (auto&& [_, t] : ma) { times.push_back(t); } sort(times.begin(), times.end()); int ans = 0; for (int cnt = 0, i = times.size() - 1; cnt < arr.size() / 2; ans++, i--) { cnt += times[i]; } return ans; } };
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14
from typing importList from collections import Counter
classSolution: defminSetSize(self, arr: List[int]) -> int: ma = Counter(arr) times = [t for i, t in ma.items()] times.sort() ans, cnt, i = 0, 0, len(times) - 1 while cnt < len(arr) // 2: ans += 1 cnt += times[i] i -= 1 return ans
funcminSetSize(arr []int) (ans int) { ma := map[int]int{} for _, t := range arr { ma[t]++ } var times []int for _, t := range ma { times = append(times, t) } sort.Slice(times, func(i, j int)bool { return times[i] > times[j] }) for cnt := 0; cnt < len(arr) / 2; ans++ { cnt += times[ans] } return }