晨哥Leetcode 992. Subarrays with K Different Integers

Given an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A good if the number of different integers in that subarray is exactly K.
(For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.)
Return the number of good subarrays of A.
Example 1:
Input: A = [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: A = [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].

解析:
网上很多算法我都看不懂,找了这种最容易懂的
恰好为K的 = 最多为k的数量 - 最多为k-1的数量

怎么算最多为k的数量?
统计数量时思路要清晰,j一直向右遍历的时候,找出以当前j结尾的,所有符合要求的情况
统计时关注两点:

  1. 要保证当前 i…j 窗口小于等于K, 是符合要求的
  2. 盯着这个当前j, 以j结尾的数量为i-j+1
public int subarraysWithKDistinct(int[] a, int k) {
        return atMost(a, k) - atMost(a, k-1);
    }
    
    private int atMost(int[] a, int k) {//less or equal to
        int i = 0, j =0;
        Map<Integer, Integer> map = new HashMap();
        int res = 0;
        for(; j < a.length; j++) {
            map.put(a[j], map.getOrDefault(a[j], 0) + 1);
            while(map.size() > k) {// >k是不能算进去的,先把前面的i收缩到符合要求为止
                int cur = map.get(a[i]);
                if(cur == 1) 
                    map.remove(a[i]);
                else 
                    map.put(a[i], cur-1);
                i++;
            }
            res+= j-i+1;// 以j结尾的所有组合数是j-i+1
        }
        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值