题目
You are given an integer array nums and an integer k.
In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.
Return the maximum number of operations you can perform on the array.
解题思路
使用一个计数器求出每个数出现的次数,遍历计数器,找到当前数字与其对应数字出现的较少次数,单独处理k/2
的情况
代码
class Solution:
def maxOperations(self, nums: List[int], k: int) -> int:
ct = Counter(nums)
res = 0
for n in ct:
tmp = k - n
if n == tmp:
res += ct[n] // 2
continue
if n < tmp:
res += min(ct[n], ct[tmp])
return res