2958. Length of Longest Subarray With at Most K Frequency - Medium

前往題目

想法

  • 經典Sliding window

思路

  1. 左右指針
  2. 每次循環移動右指針,更新右指針數字的數量
  3. 如果發現invalid window移動左指針直到windowvalid
  4. 更新window的大小

這次完整的自己寫出來一次AC,而且花不到兩分鐘👍

Code

class Solution {
    public int maxSubarrayLength(int[] nums, int k) {
        int l = 0;
        // number -> counts
        HashMap<Integer, Integer> count = new HashMap();
        int res = 0; // max window size

        for (int r = 0; r < nums.length; ++r) {
            // Update current number's count
            count.put(nums[r], count.getOrDefault(nums[r], 0) + 1);
            
            // Invalid window occurs, fix it
            while (l <= r && count.getOrDefault(nums[r], 0) > k) {
                // Remove the number of left pointer
                count.put(nums[l], count.getOrDefault(nums[l], 1) - 1);

                // Move left pointer
                ++l;
            }

            // Update max window
            res = Math.max(res, r - l + 1);
        }
        return res;
    }
}

2958. Length of Longest Subarray With at Most K Frequency - Medium
https://f88083.github.io/2024/07/29/2958-Length-of-Longest-Subarray-With-at-Most-K-Frequency/
作者
Simon Lai
發布於
2024年7月29日
許可協議