题解 | #最长无重复子数组#

最长无重复子数组

http://www.nowcoder.com/practice/b56799ebfd684fb394bd315e89324fb4

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<>(); //1.创建一个hashset集合
        int left = 0;  //2.通过滑动窗口的方法
        int right = 0;
        int max = 0;
        while(right < arr.length){
            while(set.contains(arr[right])){ //3.如果右边界遇到重复的,将左边界的值从集合
                set.remove(arr[left++]);//中删除,然后移动左边界,然后再进行判断
            }
            set.add(arr[right++]); //如果在集合中没包含该值得话就直接将该值加入集合然后右边界向右移动
            max = Math.max(max,right-left); //然后再找出最长的数组的长度
        }
        return max;
    }
}
全部评论

相关推荐

点赞 评论 收藏
转发
1 收藏 评论
分享
牛客网
牛客企业服务