Re: [閒聊] 每日leetcode已回收
https://leetcode.com/problems/length-of-longest-subarray-with-at-most-k-frequency
2958. Length of Longest Subarray With at Most K Frequency
給你一個陣列 nums 和一個數字 k,如果一個子陣列滿足所有數字的出現次數都不超過 k
,他是一個 good 陣列,找出最長的 goood 子陣列長度。
思路:
1.找滿足條件的子陣列 -> 滑動窗口,維護一個窗口並記錄窗口中這個數字出現的次數,
如果超過 k 次就把窗口左邊的元素pop直到滿足小於等於k。
2.每次用當前窗口的大小更新解。
pycode:
----------------------------------------------
class Solution:
def maxSubarrayLength(self, nums: List[int], k: int) -> int:
dict = defaultdict(int)
l = 0
res = 0
for r in range(len(nums)):
dict[nums[r]] += 1
while dict[nums[r]] > k:
dict[nums[l]] -= 1
l += 1
res = max(res, r - l + 1)
return res
----------------------------------------------
--
https://i.imgur.com/4nfnn6f.jpg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 101.138.8.233 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1711587965.A.234.html
→
03/28 09:12,
1年前
, 1F
03/28 09:12, 1F
推
03/28 09:25,
1年前
, 2F
03/28 09:25, 2F
討論串 (同標題文章)
完整討論串 (本文為第 74 之 1548 篇):