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

最长无重复子数组

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;
    }
}
全部评论

相关推荐

写不来代码的小黑:这么小的城市能有做it的公司也不容易
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 11:30
找工作7个月,投了7000封,3段世界五百强实习,才有一个offer,牛油们肯定比我强吧
码农索隆:不对不对不对,实习经历这么厉害,简历也没少投,问题出在哪呢
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务