【找出最长等值子数组】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
相关推荐
BirdenT11 小时前
20260518紫题训练
c++·算法
databook11 小时前
切线的魔法:用 SymPy 和 Manim 轻松搞定导数动画
python·数学·动效
程序员榴莲11 小时前
Python 正则表达式入门:从匹配手机号到提取文本内容
python·正则表达式
程序员榴莲12 小时前
Python 中的 @property:像访问属性一样调用方法
开发语言·前端·python
坐吃山猪12 小时前
【Nanobot】README04_LEVEL2 提供商系统设计
python·源码·agent·nanobot
玛卡巴卡ldf12 小时前
【LeetCode 手撕算法】(多维动态规划)不同路径、最小路径和、最长回文子串、最长公共子序列、编辑距离
java·数据结构·算法·leetcode·动态规划·力扣
坐吃山猪12 小时前
【Nanobot】README09_LEVEL4 添加新聊天渠道
开发语言·网络·python·源码·nanobot
被AI抢饭碗的人12 小时前
算法:数据结构
数据结构·算法
运筹vivo@12 小时前
leetcode每日一题: 跳跃游戏 IV
leetcode·游戏·宽度优先
_深海凉_12 小时前
LeetCode热题100-验证二叉搜索树
算法·leetcode·职场和发展