【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