标签 |
---|
双指针 |
题目
https://leetcode-cn.com/problems/subarrays-with-k-different-integers/
分析
代码
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)