AcWing 651. 逛画展
原题链接
简单
作者:
两者
,
2025-03-03 20:21:25
· 福建
,
所有人可见
,
阅读 3
算法1
滑动窗口 O(n)
Java 代码
import java.io.*;
import java.util.*;
public class Main{
static BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(System.out));
static int[] set=new int[2002];
static int[] a=new int[1000005];
static int hh=0;
static int tt=-1;
static int cnt=0;
public static void main(String args[]) throws IOException{
String[] s1=reader.readLine().split(" ");
int n=Integer.parseInt(s1[0]);
int maxa=0,maxb=n-1;
int m=Integer.parseInt(s1[1]);
String[] s=reader.readLine().split(" ");
for(int i=0;i<n;i++){
a[i]=Integer.parseInt(s[i]);
}
for(int i=0;i<n;i++){
if(set[a[i]]==0){
for(int j=tt+1;j<=i;j++){
if(set[a[j]]++==0)cnt++;
}
tt=i;
while(set[a[hh]]>1){set[a[hh]]--;hh++;}
if(cnt==m){
if(tt-hh<maxb-maxa){maxa=hh;maxb=tt;}
set[a[hh]]--;hh++;cnt--;
}
}
}
writer.write((maxa+1)+" "+(maxb+1));
writer.flush();
writer.close();
reader.close();
}
}