📅  最后修改于: 2023-12-03 15:26:53.345000             🧑  作者: Mango
问题描述:给定一个整数数组和一个整数K,找出每个大小为K的子数组中的最大唯一元素。如果子数组中存在多个最大唯一元素,则返回其中任何一个。
示例:
Input: nums = [1,2,1,3,3,2], k = 2
Output: [2,2,3,3,2]
Explanation: Size 2 subarrays are [1,2], [2,1], [1,3], [3,3], [3,2]. The maximum unique value of each subarray is as follows:
[2,2,3,3,2]
解决方案:使用哈希表和双端队列(deque)。
步骤:
参考代码:
from collections import deque
class Solution:
def maxUnique(self, nums: List[int], k: int) -> List[int]:
queue = deque()
count_dict = {}
result = []
for i, num in enumerate(nums):
queue.append(num)
count_dict[num] = count_dict.get(num, 0) + 1
if len(queue) > k:
leftmost = queue.popleft()
count_dict[leftmost] -= 1
if count_dict[leftmost] == 0:
del count_dict[leftmost]
if len(queue) == k:
unique = [key for key, val in count_dict.items() if val == 1]
if not unique:
result.append(-1)
else:
result.append(max(unique))
return result
此代码片段是python代码,可通过markdown语法渲染为代码块。