Re: [閒聊] 每日leetcode已回收

看板Marginalman作者 (みけねこ的鼻屎)時間1年前 (2024/03/28 09:06), 編輯推噓1(101)
留言2則, 2人參與, 1年前最新討論串74/1548 (看更多)
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
文章代碼(AID): #1c1C9z8q (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1c1C9z8q (Marginalman)