题目大意:
给你一串数字:你就是要找出那串数字中首尾相同的某个子串,这样的子串可能存在多个,找出最小子段的长度
看一眼数据,如果暴力一点,复杂度是n^2;那就是两百万的计算量,而计算机一秒是一百多万,估计会TLE;
所以我们想到了一个类似桶排序的思路??
看看代码???
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
const int maxn = 200005;
int a, st[maxn];
int main()
{
int t;
int n;
scanf_s("%d", &t);
while (t--)
{
int flag = 0;
int ans = 9999999;
memset(st, 0, sizeof(st));
scanf_s("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf_s("%d", &a);
if (st[a] == 0)
st[a] = i;
else
{
flag = 1;
ans = min(ans, i - st[a]);
st[a] = i;
}
}
if (!flag)//就是flag==0的意思;
printf("-1\n");
else
printf("%d\n", ans+1);
}
return 0;
}
开了一个记录数组,他的作用是记录这个数的下标,先全部变成0,然后逐个记录,这样时间复杂度就是O(n)了,棒!
至于我为什么会提到桶排序呢
因为我觉得是有点类似的,桶排序的简单版本是记录这个数出现的次数,我再去学习一下!以后再更!