方法一:左右指针,left,right控制窗口的边界,当right++后,i遍历left~right-1位置的值是否与right处的值是否相等,若相等则left=i+1,统计res=max(res, right-left+1)即可.
class Solution {
public:
/**
*
* @param arr int整型vector the array
* @return int整型
*/
int maxLength(vector<int>& arr) {
// write code here
int n = arr.size();
int left = 0;
int right = 1;
int res = 1;
while(right < n)
{
for(int i=left;i<right;i++)
if(arr[i]==arr[right]){
left = i+1;
break;
}
res = max(res, right-left+1);
right++;
}
return res;
}
};
方法二:哈希,map<值,位置>
class Solution {
public:
/**
*
* @param arr int整型vector the array
* @return int整型
*/
int maxLength(vector<int>& arr) {
// write code here
int n = arr.size();
int left = 0;
int right = 1;
int res = 1;
unordered_map<int, int> my_map;
my_map[arr[left]] = left;
while(right < n)
{
if(my_map.find(arr[right])!=my_map.end())
{
int i = left;
int j = my_map[arr[right]];
left = my_map[arr[right]] + 1;
for(; i<j; i++)
my_map.erase(arr[i]);
}
my_map[arr[right]] = right;
res = max(res, right-left+1);
right++;
}
return res;
}
};