(left,right)表示当前子数组,逐次比较,找到最长的子数组。
import java.util.*;
public class Solution {
/**
*
* @param arr int整型一维数组 the array
* @return int整型
*/
public int maxLength (int[] arr) {
// write code here
HashSet<Integer> set = new HashSet<>();
int left = 0,right = 0;
int max = 0;
while (right<arr.length){
if(!set.contains(arr[right])){
set.add(arr[right]);
right++;
}else {
max = max>right-left?max:right-left;
set.clear();
left = left+1;
right = left;
}
}
return max>right-left?max:right-left;
}
}

京公网安备 11010502036488号