算法练习10——数组为空的最少操作次数

文章讲述了在LeetCode题目中,如何通过排序和使用Counter数据结构优化算法,减少在给定数组中通过删除相等元素使数组变为空的操作次数。作者提供了两种解决方案,一种是原始的排序并遍历,另一种是利用Counter计算每个元素出现次数并根据规则求解最少操作次数。
摘要由CSDN通过智能技术生成

LeetCode 100032 使数组为空的最少操作次数

给你一个下标从 0 开始的正整数数组 nums 。
你可以对数组执行以下两种操作 任意次 :
从数组中选择 两个 值 相等 的元素,并将它们从数组中 删除 。
从数组中选择 三个 值 相等 的元素,并将它们从数组中 删除 。
请你返回使数组为空的 最少 操作次数,如果无法达成,请返回 -1 。

我的超长代码,没有下面这个sort就超时了…

class Solution:
    def minOperations(self, nums: List[int]) -> int:
        nums.sort()
        times = 0
        repeat_times, repeat_item = 0, nums[0]
        for idx, item in enumerate(nums):
            if item == repeat_item:
                repeat_times += 1
            if item != repeat_item:
                if repeat_times % 3 == 0:
                    times += repeat_times // 3
                elif repeat_times % 3 == 1:
                    if repeat_times > 3:
                        times += repeat_times // 3 - 1 + 2
                    else:
                        return -1
                else:
                    times += repeat_times // 3 + 1
                
                repeat_times = 1
                repeat_item = item
        if repeat_times % 3 == 0:
            times += repeat_times // 3
        elif repeat_times % 3 == 1:
            if repeat_times > 3:
                times += repeat_times // 3 - 1 + 2
            else:
                return -1
        else:
            times += repeat_times // 3 + 1
        
        return times

使用Counterc + 2 // 3完美避免了冗长的代码

class Solution:
    def minOperations(self, nums: List[int]) -> int:
        cnt = Counter(nums)
        if 1 in cnt.values():
            return -1
        return sum((c + 2) // 3 for c in cnt.values())

# 作者:灵茶山艾府
# 链接:https://leetcode.cn/problems/minimum-number-of-operations-to-make-array-empty/
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值