首页 > 技术文章 > 【C/C++】最长无重复子数组

kinologic 2021-05-13 18:08 原文

题目描述
给定一个数组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");
}

推荐阅读