# 较难题:最长无重复数组

XAMPP相关 493浏览

## 示例1

`[2,3,4,5]`

`4`

`[2,3,4,5]是最长子数组`

## 示例2

`[2,2,3,4,3]`

`3`

[2,3,4]是最长子数组

Java版：

``````public int maxLength (int[] arr) {
``````        // write code here
``````        int result=0;
``````        int length=arr.length;
``````        Queue<Integer> queue=new LinkedList<>();
``````        for(int c:arr)
``````        {
``````            while(queue.contains(c))
``````            {
``````                //如果有重复元素则移除队首元素，直到不重复为止
``````                queue.poll();
``````            }
``````            queue.add(c);//将元素添加到队尾
``````            result=Math.max(result,queue.size());
``````        }
``````        return result;
````    }````

Java版：

``````public static int maxLength(int []arr)
``````    {
``````        int result=0;
``````        int left=0;
``````        int length=arr.length;
``````        int right=0;
``````        Set<Integer> set=new HashSet<>();
``````        while(right<length)
``````        {
``````            while(set.contains(arr[right]))
``````                set.remove(arr[left++]);
``````            set.add(arr[right++]);
``````            result=Integer.max(result,set.size());
``````        }
``````        return result;
````    }````

C++版：使用c++来写我们可以简单一点，开一个100000个数据的数组，数组下标就是对应的值，如果数据被加进去就把数组数据设置为1，没有加就设置为0。用空间换取时间，下面请看代码：

``````int maxLength(vector<int> arr)
``````{
``````  int left=0;
``````  int right=0;
``````  int Max=0;//记录不重复元素最大数量
``````  int length=arr.size();
``````  vector<int>v(100000);//开一个100000个元素的数组，且值初始化为0
``````  while(right<length)
``````  {
``````     //如果v[arr[right]]!=0，说明v中包含这个数据，
``````    //那就删除走指针所指的数据，且做指针享有移动一位
``````    while(v[arr[right]]!=0)
``````      v[arr[left++]]=0;
``````    //v中添加右指针所指的数据，且右指针向右移动一位
``````    v[arr[right++]]=1;
``````    Max=max(Max,right-left);
``````  }
``````  return Max;
````}````