python
class Solution:
def longestEqualSubarray(self, nums: List[int], k: int) -> int:
n=len(nums)
if n<2:
return n
mx=1
for i,num in enumerate(nums):
error=0
flag=1
for j in range(i+1,n):
if nums[j]==num:
flag+=1
mx=max(mx,flag)
else:
error+=1
if error>k:
break
return mx
暴力循环超时
使用双指针改造
python
class Solution:
def longestEqualSubarray(self, nums: List[int], k: int) -> int:
d, ans = defaultdict(list), 1
for i, x in enumerate(nums): d[x].append(i)
for lst in d.values():
i, j, n = 0, 0, len(lst)
while i < n:
while j < n and lst[j] - lst[i] <= j - i + k: j += 1
ans, i = max(ans, j - i), i + 1
return ans