題目描述
給定一個數組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");
}