题解 | #最长无重复子数组#
最长无重复子数组
http://www.nowcoder.com/practice/b56799ebfd684fb394bd315e89324fb4
map的简单运用
class Solution {
public:
/**
*
* @param arr int整型vector the array
* @return int整型
*/
map<int,int> mp;
int maxLength(vector<int>& arr) {
// write code here
int maxlen = 1,first = 0;
for(int i = 0,len = 0;i < arr.size();++i){
if(mp.find(arr[i]) == mp.end()){
mp[arr[i]] = i;
len ++;
}
else{
int start = mp[arr[i]];
int templen = start - first + 1;
len = len - templen + 1;
//清除无效的标识
for(int j = first;j <= start;++j)
mp.erase(arr[j]);
mp[arr[i]] = i;
first = start + 1;
}
maxlen = max(maxlen,len);
}
return maxlen;
}
};