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

129 篇文章 0 订阅
60 篇文章 0 订阅

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;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值