Table of Contents
一、中文版
给你一个整数数组 arr 和一个整数 k 。现需要从数组中恰好移除 k 个元素,请找出移除后数组中不同整数的最少数目。
示例 1:
输入: arr = [5,5,4], k = 1
输出: 1
解释: 移除 1 个 4 ,数组中只剩下 5 一种整数。
示例 2:
输入: arr = [4,3,1,1,3,3,2], k = 3
输出: 2
解释: 先移除 4、2 ,然后再移除两个 1 中的任意 1 个或者三个 3 中的任意 1 个,最后剩下 1 和 3 两种整数。
提示:
1 <= arr.length <= 10^51 <= arr[i] <= 10^90 <= k <= arr.length
二、英文版
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^51 <= arr[i] <= 10^90 <= k <= arr.length
三、My answer
class Solution:
def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
counter = collections.Counter(arr)
arr_dict = dict(counter) # 转化为字典
new_dict = sorted(arr_dict.items(), key = lambda item : item[1])
res = len(new_dict)
for key, val in new_dict:
if val <= k:
res -= 1
k = k - val
else:
break
return res
四、解题报告
数据结构:哈希(Python 中可用字典实现哈希功能)
算法:遍历字典
实现:
1、使用自带的 collections.Counter() 函数统计数组 arr 中每个元素的个数,并按照个数进行升序排序。
2、升序排序之后,遍历时就会先减掉个数小于 k 的数字,并用 k-val 不断更新 k 的值。
假设留下来的数字的个数都大于此时的 k 值,说明不会再减少题意中所求的个数了。