Leetcode 2958. Length of Longest Subarray With at Most K Frequency

1. 解题思路

这一题思路上其实也很简单,就是一个滑动窗口的思路,遍历窗口的左边界,平移获得使得其内部字符的frequency不超过k的最大右边界,然后取各个窗口长度的最大值即可。

显然左右边界都是单调的,因此整体算法复杂度就是 O ( N ) O(N) O(N)

2. 代码实现

给出python代码实现如下:

class Solution:
    def maxSubarrayLength(self, nums: List[int], k: int) -> int:
        i, j, n = 0, 0, len(nums)
        cnt = defaultdict(int)
        ans = 0
        while j < n:
            x = nums[j]
            cnt[x] += 1
            j += 1
            while cnt[x] > k:
                cnt[nums[i]] -= 1
                i += 1
            ans = max(ans, j-i)
        return ans

提交代码评测得到:耗时1272ms,占用内存31.2MB。

相关推荐

  1. LeetCode258. 各位相加

    2023-12-12 01:02:01       60 阅读
  2. LeetCode258. Add Digits

    2023-12-12 01:02:01       66 阅读
  3. Leetcode 2959. Number of Possible Sets of Closing Branches

    2023-12-12 01:02:01       65 阅读
  4. leetcode 2952.需要添加的硬币的最小数量

    2023-12-12 01:02:01       37 阅读
  5. leetcode 2938.区分白球与黑球

    2023-12-12 01:02:01       29 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-12 01:02:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-12 01:02:01       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-12 01:02:01       82 阅读
  4. Python语言-面向对象

    2023-12-12 01:02:01       91 阅读

热门阅读

  1. 通义千问测试

    2023-12-12 01:02:01       55 阅读
  2. 使用OkHttp上传本地图片及参数

    2023-12-12 01:02:01       58 阅读
  3. 空间信息智能应用团队研究成果与人才引进

    2023-12-12 01:02:01       52 阅读
  4. Zookeeper面试题

    2023-12-12 01:02:01       60 阅读
  5. 安装CAS登录服务器

    2023-12-12 01:02:01       57 阅读
  6. C++ Primer Plus第十五章笔记

    2023-12-12 01:02:01       38 阅读
  7. RK3568 CIF和ISP的关联

    2023-12-12 01:02:01       65 阅读
  8. 云计算核心技术

    2023-12-12 01:02:01       57 阅读