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

  • [Leetcode 2958. Length of Longest Subarray With at Most K Frequency](#Leetcode 2958. Length of Longest Subarray With at Most K Frequency)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

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

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

2. 代码实现

给出python代码实现如下:

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。

相关推荐
Espresso Macchiato1 天前
Leetcode 3568. Minimum Moves to Clean the Classroom
剪枝·广度优先遍历·leetcode medium·堆排·leetcode周赛452·leetcode 3568
Espresso Macchiato5 天前
Leetcode 3567. Minimum Absolute Difference in Sliding Submatrix
leetcode·leetcode medium·leetcode周赛452·leetcode 3567
Espresso Macchiato5 天前
Leetcode 3566. Partition Array into Two Equal Product Subsets
动态规划·leetcode medium·leetcode 3566·leetcode周赛452
GEEK零零七6 天前
Leetcode 159. 至多包含两个不同字符的最长子串
算法·leetcode·滑动窗口
Espresso Macchiato10 天前
Leetcode 3557. Find Maximum Number of Non Intersecting Substrings
动态规划·leetcode medium·leetcode 3557·leetcode双周赛157
Espresso Macchiato19 天前
Leetcode 3552. Grid Teleportation Traversal
广度优先遍历·leetcode medium·leetcode周赛450·leetcode 3552·堆排
Espresso Macchiato19 天前
Leetcode 3551. Minimum Swaps to Sort by Digit Sum
leetcode·排序·leetcode medium·leetcode 3551·leetcode周赛450
Espresso Macchiato22 天前
Leetcode 3543. Maximum Weighted K-Edge Path
leetcode·leetcode medium·图遍历·leetcode 3543·leetcode双周赛156
卷卷的小趴菜学编程1 个月前
算法篇-----滑动窗口
数据结构·算法·双指针·滑动窗口·哈希表·数组相关
满怀10151 个月前
【数据通信完全指南】从物理层到协议栈的深度解析
5g·滑动窗口·数据封装·crc校验·qam调制