Given an array of integers arr
and an integer k
. Find the least number of unique integers after removing exactly k
elements.
Example 1:
Input: arr = [5,5,4], k = 1 Output: 1 Explanation: Remove the single 4, only 5 is left.
Example 2:
Input: arr = [4,3,1,1,3,3,2], k = 3 Output: 2 Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 10^9
0 <= k <= arr.length
题目给定一个数组arr和一个整数,问从数组中删除k个数后所剩下的最少的唯一整数的个数是多少?
本着贪心原则,要使得最后剩下的唯一整数个数最少,那就要尽可能多地删除唯一整数,尽量让出现频率高的数留下。很显然我们应该从出现频率最少的数开始删除,比如先删只出现一次的数,不够k个就继续删出现两次的数,还不够就删出现三次的数...,以此类推直到删除k个数为止。这样最后剩下的唯一整数的个数是最少的。
要达到以上目的,首先要统计一下每个数在数组中出现的频率,然后再统计一下每种频率下有多少个数,最后按频率从低到高的顺序删除掉k个数。
from sortedcontainers import SortedDict
class Solution:
def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
counts = collections.Counter(arr)
n = len(counts) #含有n个唯一整数
freq = SortedDict()
for cnt in counts.values():
if cnt in freq:
freq[cnt] += 1
else:
freq[cnt] = 1
#key 是频率,val是该频率下数的个数
for key,val in freq.items():
# kwy * val是当前频率下要全删除的次数,少于k个就把该频率下的数全删掉
if key * val < k:
k -= key * val
n -= val #删掉了val个唯一整数
else:
#不够全删除当前频率下所有数,那么删除k次后被删掉的唯一整数个数是k//key
n -= k // key
k = 0
return n