题解 | #最长无重复子数组#
最长无重复子数组
http://www.nowcoder.com/practice/b56799ebfd684fb394bd315e89324fb4
此文仅用于本人记录
双指针的题目配合哈希表,属于是固定模板了。
双指针,右指针一旦(用哈希表检测比较快)检测到重复的就挪动左指针。
每次记录的范围是[left,right]。
import java.util.*; public class Solution { /** * * @param arr int整型一维数组 the array * @return int整型 */ public int maxLength (int[] arr) { // write code here if(arr.length == 1){ return 1; } HashMap<Integer,Integer> hashMap = new HashMap<>(); int left = 0; int right = left+1; //[left,right) hashMap.put(arr[left],0); int maxResult = 1; while(right != arr.length){ if(hashMap.containsKey(arr[right]) == true){ int oldLeft = left; left = hashMap.get(arr[right]) +1; for(int i = oldLeft;i < left;i++){ hashMap.remove(arr[i]); } } hashMap.put(arr[right],right); maxResult = Math.max(maxResult,(right - left+1)); right++; } return maxResult; } }