【C/C++】最长无重复子数组


题目描述
给定一个数组arr,返回arr的最长无重复元素子数组的长度,无重复指的是所有数字都不相同。
子数组是连续的,比如[1,2,3,4,5]的子数组有[1,2],[2,3,4]等等,但是[1,3,4]不是子数组

#include <bits/stdc++.h>
using namespace std;

class Solution
{
public:
    int maxLength(vector<int> & arr)
    {
        int maxlen = 0;
        set<int> st;
        int i = 0, j = 0;
        while( j < arr.size())
        {
            while(st.count(arr[j]))
            {
                st.erase(arr[i++]);
            }
            st.insert(arr[j++]);
            maxlen = max(maxlen, j - i);
        }
        return maxlen;

    }
};

int main()
{
    vector <int> arr = {2,2,3,4,3};
    Solution solution;
    cout << solution.maxLength(arr) << endl;
    system("pause");
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM