去除K挑战后的唯一整数的最少数量

问题描述 投票:0回答:1

挑战如下:

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

而且我很难理解一个人对此的解决方案。有人会很好地解释他的最佳解决方案是如何工作的吗?在最近的leetcode竞赛中,这是一个新的挑战,没有重复的挑战。

    def findLeastNumOfUniqueInts3(self, A, K):
        count = collections.Counter(A)
        items = list(count.items())
        items.sort(key=lambda e: e[1])
        ans = len(items)
        for i, (_, x) in enumerate(items):
            if K >= x:
                K -= x
                ans -= 1
        return ans
python python-3.x collections dynamic-programming leetcode
1个回答
0
投票

首先,此人使用计数器(集合)对数字进行单独计数

比方说,您的输入列表为[4,3,1,1,3,3,2],则该列表的单个计数变为:

number     count
  4    ->    1
  3    ->    3
  1    ->    2
  2    ->    1

排序后:

number     count
  4    ->    1
  2    ->    1
  1    ->    2
  3    ->    3

现在您可以删除K个数字,以得到最少的唯一数字,这里的直觉是,我们首先从出现次数最少的数字开始,以便我们可以删除最大的唯一数字,从而得到最少的唯一数字(这是需要的)。

现在,他遍历排序的项目计数列表,如果当前项目的计数小于K,则推导K的值,他遍历直到K == 0或我们遍历整个列表。如果一个项目的计数小于K,我们可以增加计数,并可以从给定列表的唯一数字的长度推导出该计数。

这是我的解决方法:

from collections import defaultdict 

def uns(A, K):
    icounts = defaultdict(lambda:0)
    for x in A:
        icounts[x]+=1

    counts = [icounts[i] for i in icounts]
    counts = sorted(counts)

    rem = 0
    for x in counts:
        if K>=x:
            rem+=1
            K-=x
        if(K==0):
            break

    return len(counts)-rem
print(uns([4,3,1,1,3,3,2],3))

输出:

2

希望您能理解我的解释。

© www.soinside.com 2019 - 2024. All rights reserved.