1. 题目
2. 思路
(1) 模拟法
- 利用HashSet存储当前左右指针区间内的元素,维护一个全局最长无重复子数组的长度即可。
3. 代码
import java.util.HashSet;
import java.util.Set;
public class Test {
public static void main(String[] args) {
}
}
class Solution {
/**
* @param arr int整型一维数组 the array
* @return int整型
*/
public int maxLength(int[] arr) {
int n = arr.length;
int res = 1;
int left = 0;
int right = 0;
Set<Integer> set = new HashSet<>();
while (right < n) {
while (right < n && set.add(arr[right])) {
right++;
}
res = Math.max(res, right - left);
if (right == n) {
return res;
}
while (left < n && arr[left] != arr[right]) {
set.remove(arr[left]);
left++;
}
left++;
right++;
}
return res;
}
}