题解 | 最长无重复子数组
最长无重复子数组
https://www.nowcoder.com/practice/b56799ebfd684fb394bd315e89324fb4
import java.util.*; public class Solution { /** * 使用两个指针和一个 hash 表,hash 表用来维护子串中数字和下标 * 首先固定一个指针,另外一个指针往后走,每遍历一个数字就将判断一下这个数字在 hash 表中是否存在 * 如果这个数字在 hash 表中存在,说明出现了重复,这个时候就找到了一个子串,记录它的长度,去除这个数字在 hash 表中的下标,left 和 right 都拨到小表的下一个位置,继续遍历 * 如果这个数字在 hash 表中不存在,说明 没有出现重复,将这个数字加入 hash 表中,然后继续往后走 */ 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) { if (map.containsKey(arr[i])) { j = Math.max(j, map.get(arr[i]) + 1); } map.put(arr[i], i); max = Math.max(max, i - j + 1); } return max; } }