Re: [閒聊] 每日leetcode

看板Marginalman作者 (早瀬ユウカの体操服 )時間1年前 (2024/12/14 18:00), 編輯推噓1(100)
留言1則, 1人參與, 1年前最新討論串1205/1554 (看更多)
※ 引述《dont (dont)》之銘言: : 2762. Continuous Subarrays 今天這題好麻煩喔 算滿足條件的子陣列數量會想到用滑動窗口 陣列可能會是 [5,3,7] 或 [5,7,3] 這種CASE 不能只檢查窗口的頭部,要找到窗口裡的最大值和最小值比較 然後一直POP到兩個條件都滿足 如果不call treemap這種map+實作排序的資料結構真的會麻煩要死 Java code: ------------------------------------------------------ class Solution { public long continuousSubarrays(int[] nums) { int n = nums.length; long res = 0; int l = 0; TreeMap<Integer, Integer> map = new TreeMap<>(); for (int r = 0; r < n; r++) { int min = map.isEmpty() ? nums[r] : map.firstKey(); while (Math.abs(min - nums[r]) > 2) { decreaseCountMap(map, nums[l++]); min = map.isEmpty() ? nums[r] : map.firstKey(); } int max = map.isEmpty() ? nums[r] : map.lastKey(); while (Math.abs(max - nums[r]) > 2) { decreaseCountMap(map, nums[l++]); max = map.isEmpty() ? nums[r] : map.lastKey(); } map.put(nums[r], map.getOrDefault(nums[r], 0) + 1); res += (r - l + 1); } return res; } void decreaseCountMap(Map<Integer, Integer> map, int val) { if (map.get(val) == 1) { map.remove(val); } else { map.put(val, map.get(val) - 1); } } } ----------------------------------------------------------- -- https://i.imgur.com/R8vs1tZ.jpeg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.158.191.3 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1734170422.A.C5F.html

12/14 18:20, 1年前 , 1F
用monotonic stack
12/14 18:20, 1F
文章代碼(AID): #1dNLSsnV (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1dNLSsnV (Marginalman)