美文网首页Leetcode
Leetcode 1481. Least Number of U

Leetcode 1481. Least Number of U

作者: SnailTyan | 来源:发表于2021-02-20 13:03 被阅读0次

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Least Number of Unique Integers after K Removals

2. Solution

  • Version 1
class Solution:
    def findLeastNumOfUniqueInts(self, arr, k):
        stat = {}
        for num in arr:
            stat[num] = stat.get(num, 0) + 1
        result = sorted(stat.items(), key=lambda item: item[1])
        while k > 0:
            k = k - result[0][1]
            if k >= 0:
                result.pop(0)
        return len(result)
  • Version 2
class Solution:
    def findLeastNumOfUniqueInts(self, arr, k):
        stat = {}
        for num in arr:
            stat[num] = stat.get(num, 0) + 1
        result = sorted(stat.items(), key=lambda item: item[1])
        index = 0
        while k > 0:
            k = k - result[index][1]
            if k >= 0:
                index += 1
        return len(result) - index
  • Version 3
class Solution:
    def findLeastNumOfUniqueInts(self, arr, k):
        stat = {}
        for num in arr:
            stat[num] = stat.get(num, 0) + 1
        result = sorted(arr, key=lambda num: (stat[num], num))
        return len(set(result[k:]))

Reference

  1. https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/

相关文章

网友评论

    本文标题:Leetcode 1481. Least Number of U

    本文链接:https://www.haomeiwen.com/subject/vzvqxltx.html