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。

相关推荐
硕风和炜2 天前
【LeetCode:3101. 交替子数组计数 + 滑动窗口 + 数学公式】
java·数学·算法·leetcode·滑动窗口
linweidong5 天前
Flink 时间窗口在 IoT 项目中的应用实战
物联网·flink·iot·滚动窗口·滑动窗口·时间窗口
Espresso Macchiato6 天前
Leetcode 3201. Find the Maximum Length of Valid Subsequence I
leetcode medium·leetcode题解·leetcode 3201·leetcode周赛404
源代码:趴菜11 天前
leetcode209:长度最小的子数组
算法·leetcode·滑动窗口
Espresso Macchiato13 天前
Leetcode 3196. Maximize Total Cost of Alternating Subarrays
leetcode·动态规划·leetcode medium·leetcode周赛403·leetcode 3196
Espresso Macchiato14 天前
Leetcode 3195. Find the Minimum Area to Cover All Ones I
leetcode·leetcode medium·leetcode题解·leetcode 3195·leetcode周赛403
Espresso Macchiato22 天前
Leetcode 3186. Maximum Total Damage With Spell Casting
动态规划·leetcode medium·leetcode题解·leetcode 3186·leetcode周赛402
Espresso Macchiato1 个月前
Leetcode 3175. Find The First Player to win K Games in a Row
leetcode medium·leetcode题解·leetcode 3175·leetcode双周赛132
DogDaoDao1 个月前
LeetCode 算法:滑动窗口最大值c++
数据结构·c++·算法·leetcode·双端队列·滑动窗口·队列
小程xy1 个月前
leetcode力扣 2024. 考试的最大困扰度
数据结构·c++·算法·leetcode·滑动窗口