输入一个长度为n(n <= 106)的序列A,找到一个尽量长的连续子序列AL~AR,使得该序列中没有相同得元素。
一开始用得map做的,用变量s存储子序列开始下标。
然后用map存储子序列中每个数字出现的下标。
然后从左到右枚举子序列结束下标i,当map[a[i]]的值不为零时,需要把map[s]~map[a[i]]的值改为0,才能继续向后扩展。
但是用map做的代码超时了,然后看了紫书中的分析,用的是set做的。
改了一下就过了。
#include <stdio.h>
#include <algorithm>
#include <set>
using namespace std;
int a[1000005];
int main()
{
int s, T, n;
scanf("%d", &T);
while(T--)
{
scanf("%d", &n);
for(int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
}
set<int> ss;
int ans = 1;
ss.insert(a[1]);
s = 1;
for(int i = 2; i <= n; i++)
{
while(ss.find(a[i]) != ss.end())
{
ss.erase(a[s++]);
}
ss.insert(a[i]);
ans = max(ans, i - s + 1);
}
printf("%d\n", ans);
}
return 0;
}
或者用map和last数组预处理后,也可以通过此题。
#include <stdio.h>
#include <algorithm>
#include <map>
using namespace std;
int a[1000005], last[1000005];
int main()
{
int s, T, n;
scanf("%d", &T);
while(T--)
{
scanf("%d", &n);
for(int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
}
map<int, int> mp;
for(int i = 1; i <= n; i++)
{
if(mp[a[i]] == 0)
last[i] = -1;
else
last[i] = mp[a[i]];
mp[a[i]] = i;
}
int ans = 1;
int s = 1;
for(int i = 2; i <= n; i++)
{
while(last[i] != -1 && last[i] >= s)
{
++s;
}
ans = max(ans, i - s + 1);
}
printf("%d\n", ans);
}
return 0;
}