问题:
给出一个数组,求至少拿出几个元素,使得他们出现的次数之和,>=总元素个数的一半
Example 1: Input: arr = [3,3,3,3,5,5,5,2,2,7] Output: 2 Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array). Possible sets of size 2 are {3,5},{3,2},{5,2}. Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has size greater than half of the size of the old array. Example 2: Input: arr = [7,7,7,7,7,7] Output: 1 Explanation: The only possible set you can choose is {7}. This will make the new array empty. Example 3: Input: arr = [1,9] Output: 1 Example 4: Input: arr = [1000,1000,3,7] Output: 1 Example 5: Input: arr = [1,2,3,4,5,6,7,8,9,10] Output: 5 Constraints: 1 <= arr.length <= 10^5 arr.length is even. 1 <= arr[i] <= 10^5
解法:
使用unordered_map存储每个元素出现的次数,
为了排序出现次数,首先将次数放入一个vector数列coutorder中。
对coutorder进行降序排序,
从头累计,sum>=1/2 arr.size()
则返回,元素个数。
代码参考:
1 class Solution { 2 public: 3 int minSetSize(vector<int>& arr) { 4 int sum=0; 5 int res=0; 6 unordered_map<int, int>cout; 7 vector<int>coutorder; 8 for(int a:arr){ 9 cout[a]++; 10 } 11 for(auto c:cout){ 12 coutorder.push_back(c.second); 13 } 14 sort(coutorder.rbegin(), coutorder.rend()); 15 for(int s:coutorder){ 16 sum+=s; 17 res++; 18 if(sum>=arr.size()/2) return res; 19 } 20 return res; 21 } 22 };