Unique Snowflakes UVA - 11572

这里写图片描述
大意:求最大不重复连续数列的长度
题解:
1.段查找问题,紫书上有,滑动窗口方式。
2.用set集合类存储,用set存数是有序的
3.先给定一个区间长度,当右端数字在set中一直没出现就一直往右扩展while(!st.count(a[r])&&r<=n) st.insert(a[r++]);
4.当重复时,去掉左端的数字st.erase(a[l++]);
5.每次更新ans值。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<set>
using namespace std;
int n,T;
long long a[1000005];
set<long long> st;
int main()
{


    cin>>T;
    while(T--)
    {
        scanf("%d",&n);
        for(int i = 1 ; i <= n ; i++)
        scanf("%lld",&a[i]);

        st.clear();

        int l = 1,r = 1,ans = 0;
        while(r<=n)
        {
            while(!st.count(a[r])&&r<=n)//一定让r<=n,不然会出现-234234234之类的a[r] 
            {
                st.insert(a[r]);
                r++;
            }
            ans = max(ans,r-l);
            if(r>n) break;//如果超过n,也没必要让下一句话继续下去了 ; 
            st.erase(a[l++]);
        }

        cout<<ans<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40240576/article/details/81592453