题意:选取一段最小的区间,此区间包含全部的知识点。
做法: 最简单的想法就是枚举所有的区间,从而找出合适并且最小的区间,这需要O(n^3)的时间复杂度,肯定超时,但是可以用来对拍用。
另一种做法便是让区间滑动,设一个区间的起点s,终点e,初始都为0,不断增加e,直到[s,e]中包含全部的知识点,此时记录下区间长度,然后s++,并且删除原先s所在的知识点,然后重复之前步骤,直到e == n && 当前知识点<总的知识点 || s == n为止,其实 s==n不写也可以,因为前者已经包含后者的情况。
最坏情况,e从0到n,s从0到n,并且加上删除的步骤(采用map)需要logn,
总的时间复杂度为O(n*n*logn)。
#include <set>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
#include <cstdio>
#include <map>
using namespace std;
const int maxn = 1000000;
int page[maxn];
set<int> read;
map<int,int> m;
int main(){
// freopen("/Users/user/Desktop/in.txt","r",stdin);
int n;
scanf("%d", &n);
for(int i = 0; i < n; ++i){
scanf("%d", &page[i]);
read.insert(page[i]);
}
int total = read.size();
read.clear();
int s = 0, e = 0;
int ans = n;
int tmp = 0;
for(;;){
while(tmp < total && e < n &&(e-s < n)){
if(!m.count(page[e]) || m[page[e]] == 0){
tmp++;
m[page[e]] = 1;
}
else
m[page[e]]++;
e++;
}
if(tmp == total){
ans = min(ans, e-s);
}
else if(tmp < total)
break;
if(m[page[s]] == 1)
tmp--;
m[page[s]]--;
s++;
if(s == n) break;
}
printf("%d\n", ans);
return 0;
}