每日一题 21.02.09 LeetCode 992.K个不同整数的子数组 java题解

标签
双指针

题目

https://leetcode-cn.com/problems/subarrays-with-k-different-integers/
每日一题 21.02.09 LeetCode 992.K个不同整数的子数组 java题解_第1张图片

分析

代码

class Solution {
     
    public int subarraysWithKDistinct(int[] A, int K) {
     
        return most(A,K)-most(A,K-1);
    }
    public static int most(int[] A,int k){
     
        int len=A.length;
        int[] f=new int[len+1];
        int left=0;
        int right=0;
        int count=0;
        int res=0;
        while(right<len){
     
            if(f[A[right]]==0){
     
                count++;
            }
            f[A[right]]++;
            while(count>k){
     
                f[A[left]]--;
                if(f[A[left]]==0){
     
                    count--;
                }
                left++;
            }
            res+=(right-left);
            right++;
        }
        return res;
    }
}

复杂度

时间复杂度O(N)
空间复杂度O(N)

你可能感兴趣的:(LeetCode,leetcode,算法,java,双指针)