题解 | #最长无重复子数组#
最长无重复子数组
http://www.nowcoder.com/practice/b56799ebfd684fb394bd315e89324fb4
import java.util.*;
public class Solution {
/**
*
* @param arr int整型一维数组 the array
* @return int整型
*/
public int maxLength(int[] arr) {
if (arr.length == 0)
return 0;
//存的是数字 数字最后一次出现的位置
HashMap<Integer, Integer> map = new HashMap<>();
int max = 0;
for (int i = 0, j = 0; i < arr.length; ++i) {
//如果当前位置在map里面
if (map.containsKey(arr[i])) {
//j代表的就是左边的界限
j = Math.max(j, map.get(arr[i]) + 1);
}
//如果不存在添加 如果存在 存的就是数字最后的下标位置了
map.put(arr[i], i);
//更新最长无重复子数组
max = Math.max(max, i - j + 1);
}
return max;
}
}
查看23道真题和解析