To minimize the number of operations, we need to delete 3 elements as much as possible. Which means we have to divide each element's count by 3, resulting in three possible scenarios:
If any element appears only once, it cannot be deleted, and the function should return -1.
為了要最小化operations次數,我們要盡可能地刪除三個相同元素,也就是找出每個元素出現次數「除以 3 的餘數」,總共有以下三種可能:
class Solution:
def minOperations(self, nums: List[int]) -> int:
if len(nums) == 2:
return 1 if nums[0] == nums[1] else -1
# Build the has map
counts = {}
for n in nums:
if n not in counts:
counts[n] = 1
else:
counts[n] += 1
operations = 0
for k, v in counts.items():
if v == 1:
return -1
r = v % 3 # remainder
q = v // 3 # quotient
if r == 0:
operations += q
else:
operations += q + 1
return operations