题解 | #最长无重复子数组#
最长无重复子数组
http://www.nowcoder.com/practice/b56799ebfd684fb394bd315e89324fb4
import java.util.*; public class Solution { /** * * @param arr int整型一维数组 the array * @return int整型 */ public int maxLength (int[] arr) { // write code here HashMap<Integer, Integer> hash = new HashMap<>(); int max = 0; int i = 0, j = 0; for (; i < arr.length; i++) { // if(hash.containsKey(arr[i])) { //如果发现重复元素,将j的值进行更新,更新原理为:始终让j指向重复值的下一个元素 j = Math.max(j, hash.get(arr[i])+1); //并同时更新重复值的新索引 hash.put(arr[i], i); }else { hash.put(arr[i], i); } //更新max的值 if (i - j + 1 > max) { max = i - j + 1; } } return max; } }