LeetCode 992 Subarrays with K Different Integers (滑动窗 推荐)

Given an integer array nums and an integer k, return the number of good subarrays of nums.

good array is an array where the number of different integers in that array is exactly k.

  • For example, [1,2,3,1,2] has 3 different integers: 12, and 3.

subarray is a contiguous part of an array.

Example 1:

Input: nums = [1,2,1,2,3], k = 2
Output: 7
Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]

Example 2:

Input: nums = [1,2,1,3,4], k = 3
Output: 3
Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].

Constraints:

  • 1 <= nums.length <= 2 * 10^4
  • 1 <= nums[i], k <= nums.length

题目链接:https://leetcode.com/problems/subarrays-with-k-different-integers/

题目大意:求恰好有k个不同数字的区间个数

题目分析:恰好有k个不好求,但至多有k个则非常容易,恰好k个=至多k个-至多k-1个,至多有k个可以用滑动窗,用hash判断每个数字出现的次数,并用一个值记录当前有多少个不同的数字

13ms,时间击败88.84%

class Solution {
    public int subarraysWithKDistinct(int[] nums, int k) {
        return atMostK(nums, k) - atMostK(nums, k - 1);
    }
    
    public int atMostK(int[] nums, int k) {
        int[] cnt = new int[20001];
        int diff = 0, ans = 0, n = nums.length, i = 0;
        for (int j = 0; j < n; j++) {
            if (cnt[nums[j]] == 0) {
                diff++;
            }
            cnt[nums[j]]++;
            while (diff > k) {
                cnt[nums[i]]--;
                if (cnt[nums[i]] == 0) {
                    diff--;
                }
                i++;
            }
            if (diff <= k) {
                ans += j - i;
            }
        }
        return ans;
    }
}

你可能感兴趣的:(数据结构,Leetcode,Hard,LeetCode,leetcode,滑动窗)