描述
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.
Note:
1 <= arr.length <= 10^5
1 <= arr[i] <= 10^9
0 <= k <= arr.length
解析
根据题意,在 arr 中去掉 k 个元素之后,最后至少剩下多少独一无二的元素。其实很好理解只要对 arr 中的元素进行计数形成字典 c ,然后按照 c 中的值进行生序排序,只要从个数最少的元素开始剔除,最后肯定越能多剔除几类元素,自然剩下的元素种类会越少。
解答
class Solution(object):
def findLeastNumOfUniqueInts(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: int
"""
c = {}
for i in arr:
if i not in c:
c[i]=1
else:
c[i]+=1
c = sorted(c.items(), key=lambda x:x[1])
n = len(c)
for key, value in c:
if value<=k:
k -= value
n -= 1
else:
break
return n
运行结果
Runtime: 432 ms, faster than 86.90% of Python online submissions for Least Number of Unique Integers after K Removals.
Memory Usage: 38.5 MB, less than 33.73% of Python online submissions for Least Number of Unique Integers after K Removals.
原题链接:https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/
您的支持是我最大的动力