思路:滑动窗口。
用两个指针记录滑动窗口的大小,用一个集合判断是否重复。如果没有重复就扩大窗口;有重复就记录此时最大长度,然后缩小窗口直到没有重复。重复以上过程。
代码:集合实现
import java.util.*;
public class Solution {
/**
*
* @param arr int整型一维数组 the array
* @return int整型
*/
public int maxLength (int[] arr) {
// write code here
Set<Integer> set = new HashSet<>();
int i = 0, j = 0;
int max = Integer.MIN_VALUE;
while (j < arr.length) {
if (set.contains(arr[j])) {
max = Math.max(max, j - i);
while (i < j) {
set.remove(arr[i]);
if (arr[i] == arr[j]) {
i ++;
break;
}
i++;
}
}
else {
set.add(arr[j]);
j ++;
}
}
max = Math.max(max, j - i);
return max;
}
}
代码:哈希实现
import java.util.*;
public class Solution {
/**
*
* @param arr int整型一维数组 the array
* @return int整型
*/
public int maxLength (int[] arr) {
// write code here
Map<Integer, Integer> map = new HashMap<>();
int i = 0, j = 0;
int max = Integer.MIN_VALUE;
while (j < arr.length) {
// 重复元素如果在左指针左侧,就不是重复。
if (map.containsKey(arr[j]) && map.get(arr[j]) >= i) {
max = Math.max(max, j - i);
i = map.get(arr[j]) + 1;
}
map.put(arr[j], j);
j ++;
}
max = Math.max(max, j - i);
return max;
}
}