双指针(同向指针)
当在含两层for循环的暴力枚举中,两个指针是可以不回退的,此时可以利用更改性质来优化时间复杂度

#include <iostream>
#include <unordered_map> mp;
using namespace std;
const int N = 1e6 + 10;
int t, n;
int a[N];//标记每一片雪花
int main()
{
cin >> t;
while (t--)
{
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
}
//定义左右指针
int l = 1, r = 1;
//用哈希表记录每种雪花出现的次数
unordered_map<int, int> mp;
int ret = 0;
while (r <= n)
{
mp[a[r]]++;
//如果区间范围内非法 则更新左指针
while (mp[a[r]] > 1)
{
//左指针退窗口
mp[a[l]]--;
l++;
}
//更新结果
ret = max(ret, r - l + 1);
r++;
}
cout << ret << endl;
}
return 0;
}
1588

被折叠的 条评论
为什么被折叠?



