【找出最长等值子数组】python

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
相关推荐
databook16 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室17 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三18 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427111 天前
Python之语言特点
python
刘立军1 天前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
聚客AI1 天前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
大怪v1 天前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django