给定一个数组arr,返回arr的最长无的重复子串的长度(无重复指的是所有数字都不相同)。
- 哈希表的使用
class Solution {
public:
/**
*
* @param arr int整型vector the array
* @return int整型
*/
int maxLength(vector<int>& arr) {
// write code here
const int len=arr.size();
int left=0,right=0;
map<int, int> haxi;
int res=0,max=0;
for(int i=0;i<len;i++){
if(haxi.find(arr[i])==haxi.end()){/*如果当前数字从未出现过,那么目前的子串长度加一,并更新当前字符的哈希表的value*/
haxi[arr[i]]=i;
res++;
}//如果当前数字出现过
else{
if(left>haxi[arr[i]]){//如果子串的起始位置在出现上一个该数字的位置之后,那么目前子串长度加一
res++;
}else{//否则 更新子串的起始位置和长度
left=haxi[arr[i]]+1;
res=i-left+1;
}
haxi[arr[i]]=i;
}
max=max>res?max:res;
}
return max;
}
};