From b6265c7e4432ee3e9379ee7c9b28423ab5876132 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D5=A1=C9=A8=D5=BC=C9=A2=D3=84=D5=A1=D6=85=D5=BC=C9=A2?= Date: Sat, 30 Mar 2024 12:40:20 +0800 Subject: [PATCH] solutions: 0992 - Subarrays with K Different Integers (Hard) --- ...ubarrays-with-k-different-integers-hard.md | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/solutions/0900-0999/0992-subarrays-with-k-different-integers-hard.md b/solutions/0900-0999/0992-subarrays-with-k-different-integers-hard.md index 43e003c78a6..cb462223f34 100644 --- a/solutions/0900-0999/0992-subarrays-with-k-different-integers-hard.md +++ b/solutions/0900-0999/0992-subarrays-with-k-different-integers-hard.md @@ -2,6 +2,7 @@ description: >- Author: @wingkwong | https://leetcode.com/problems/subarrays-with-k-different-integers/ +tags: [Array, Hash Table, Sliding Window, Counting] --- # 0992 - Subarrays with K Different Integers (Hard) @@ -43,37 +44,36 @@ Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1 ## Approach 1: Sliding Window + + ```cpp class Solution { public: - // sliding window - int go(vector& nums, int k) { - // count the frequency for each number - unordered_map cnt; - int l = 0, res = 0; - for (int r = 0; r < nums.size(); r++) { - // if nums[r] doesn't exist, we subtract k by 1 - // update cnt[nums[r]] - if (!cnt[nums[r]]++) k -= 1; - // while k < 0, we need to pop the leftmost element out - // if we remove nums[l] and its frequency is 0 - // then we can include other integer so we increase k by 1 - while (k < 0) { - if (!--cnt[nums[l]]) k += 1; - l++; - } - // add the current range to ans - res += r - l + 1; + int atMost(vector& nums, int k) { + // standard sliding window pattern + int n = nums.size(), i = 0, ans = 0; + unordered_map m; + for (int j = 0; j < n; j++) { + // step 1: make the condition invalid + k -= !m[nums[j]]++; + // step 2: if the condition is failed, + // it means we need to shrink the window + // by adding k to make the condition valid + while(k < 0) k += !(--m[nums[i++]]); + // step 3: add the distance to ans + ans += j - i + 1; } - return res; + return ans; } int subarraysWithKDistinct(vector& nums, int k) { - // exactly k differences = - // at most k differences - at most k - 1 differences - return go(nums, k) - go(nums, k - 1); + // exactky k = at most k - at most (k - 1) + return atMost(nums, k) - atMost(nums, k - 1); } }; ``` + + + \ No newline at end of file