給你一個整數數組 arr。你可以從中選出一個整數集合,并刪除這些整數在數組中的每次出現。
返回 至少 能刪除數組中的一半整數的整數集合的最小大小。
示例 1:
輸入:arr = [3,3,3,3,5,5,5,2,2,7]
輸出:2
解釋:選擇 {3,7} 使得結果數組為 [5,5,5,2,2]、長度為 5(原數組長度的一半)。
大小為 2 的可行集合有 {3,5},{3,2},{5,2}。
選擇 {2,7} 是不可行的,它的結果數組為 [3,3,3,3,5,5,5],新數組長度大于原數組的二分之一。
代碼
class Solution {public int minSetSize(int[] arr) {Map<Integer,Integer> map=new HashMap<>();double len= Math.ceil(arr.length/2);for(int c:arr)map.put(c,map.getOrDefault(c,0)+1);ArrayList<Integer> arrayList=new ArrayList<>(map.values());//記錄下不同數字的出現次數Collections.sort(arrayList, new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {return o2.compareTo(o1);}});//從大到小排序次數int temp=0;for(int i=0;i<arrayList.size();i++)//從大的出現次數開始減{temp+=arrayList.get(i);if (temp>=len) return i+1;}
return 0;}
}