描述
给定一个长度为n的数组arr,返回arr的最长无重复元素子数组的长度,无重复指的是所有数字都不相同。
子数组是连续的,比如[1,3,5,7,9]的子数组有[1,3],[3,5,7]等等,但是[1,3,7]不是子数组
题解:使用hashset元素不重复的特性,遍历各个子数组,求得最大长度
public class Solution {
/**
*
* @param arr int整型一维数组 the array
* @return int整型
*/
public int maxLength (int[] arr) {
// write code here
Set<Integer> value=new HashSet<>();
int ans=0;
for(int i=0;i<arr.length;i++)
{
int temp=0;
int j=i;
while(j<arr.length&&value.add(arr[j]))
{
temp++;
j++;
}
value.clear();
ans=Math.max(temp,ans);
}
return ans;
}
}