河北建设工程网站,网站建设进什么科目,微信公众号运营推广方案,网址大全123介绍LeetCode 100032 使数组为空的最少操作次数 给你一个下标从 0 开始的正整数数组 nums 。 你可以对数组执行以下两种操作 任意次 #xff1a; 从数组中选择 两个 值 相等 的元素#xff0c;并将它们从数组中 删除 。 从数组中选择 三个 值 相等 的元素#xff0c;并将它们从数…LeetCode 100032 使数组为空的最少操作次数 给你一个下标从 0 开始的正整数数组 nums 。 你可以对数组执行以下两种操作 任意次 从数组中选择 两个 值 相等 的元素并将它们从数组中 删除 。 从数组中选择 三个 值 相等 的元素并将它们从数组中 删除 。 请你返回使数组为空的 最少 操作次数如果无法达成请返回 -1 。 我的超长代码没有下面这个sort就超时了…
class Solution:def minOperations(self, nums: List[int]) - int:nums.sort()times 0repeat_times, repeat_item 0, nums[0]for idx, item in enumerate(nums):if item repeat_item:repeat_times 1if item ! repeat_item:if repeat_times % 3 0:times repeat_times // 3elif repeat_times % 3 1:if repeat_times 3:times repeat_times // 3 - 1 2else:return -1else:times repeat_times // 3 1repeat_times 1repeat_item itemif repeat_times % 3 0:times repeat_times // 3elif repeat_times % 3 1:if repeat_times 3:times repeat_times // 3 - 1 2else:return -1else:times repeat_times // 3 1return times使用Counter和c 2 // 3完美避免了冗长的代码
class Solution:def minOperations(self, nums: List[int]) - int:cnt Counter(nums)if 1 in cnt.values():return -1return sum((c 2) // 3 for c in cnt.values())# 作者灵茶山艾府
# 链接https://leetcode.cn/problems/minimum-number-of-operations-to-make-array-empty/
# 来源力扣LeetCode
# 著作权归作者所有。商业转载请联系作者获得授权非商业转载请注明出处。