描述
给定一个数组arr,返回arr的最长无重复元素子数组的长度,无重复指的是所有数字都不相同。
子数组是连续的,比如[1,3,5,7,9]的子数组有[1,3],[3,5,7]等等,但是[1,3,7]不是子数组
示例1
输入:
[2,3,4,5]
返回值:
4
说明:
[2,3,4,5]是最长子数组
示例2
输入:
[2,2,3,4,3]
返回值:
3
说明:
[2,3,4]是最长子数组
示例3
输入:
[9]
返回值:
1
示例4
输入:
[1,2,3,1,2,3,2,2]
返回值:
3
说明:
最长子数组为[1,2,3]
示例5
输入:
[2,2,3,4,8,99,3]
返回值:
5
说明:
最长子数组为[2,3,4,8,99]
备注:
1)方法一:
/**
*
* @param arr int整型一维数组 the array
* @return int整型
*/
// 返回最长子数组长度
/*
*/
function maxLength( arr ) {
if(!arr.length) return 0;
const map = {};
let max = 0;
let start = 0;
for(let end=0; end<arr.length; end++){
//元素arr[end]重复,重新设置start值. 不能写!map[arr[end]]
if(map[arr[end]] !== undefined){
// 重复的元素可能是start之前的,我们只考虑start~end之间的
start = Math.max(start, map[arr[end]]+1);
}
// 将当前的元素存入map(如果已存在,则更新其下标值)
map[arr[end]] = end;
max = Math.max(max, end-start+1);
}
return max;
}
module.exports = {
maxLength : maxLength
};
2) 方法二(不容易理解,建议用方法一)
/**
*
* @param arr int整型一维数组 the array
* @return int整型
*/
// 返回最长子数组长度
/*
*/
function maxLength( arr ) {
//记录当前子数组是否有重复。newArr[a] = num 表示值a 出现的次数为num
let newArr = {}
let start = 0, end = 0; //开始时,开始和结束索引均指向0
let len = arr.length;
let max = 0;
while(start < len && end < len){ //遍历数组的子数组
if(!newArr[arr[end]]){ //1. 元素arr[end]第一次出现,未重复
newArr[arr[end]] = 1; //记录当前子数组中,元素arr[end]出现依次
end++; //子数组继续向右扩展
}else{ //2. 当前子数组中,元素arr[end]已经出现过
// 此时,已找到开始索引为start的重复子串,将其出现的次数重置为0,以便下个子数组使用
newArr[arr[start]] = 0;
start++; //下一个子数组的开始索引。
}
max = Math.max(max, (end-start));
}
return max;
}
module.exports = {
maxLength : maxLength
};