题解 | #最长无重复子数组#基于滑动窗口的变形

最长无重复子数组

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

import java.util.*;


public class Solution {
    /**
     * 
     * @param arr int整型一维数组 the array
     * @return int整型
     */
    public int maxLength (int[] arr) {
        HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
        int left =0, right = 0;
        int res = 0;
        while( right < arr.length){
            hm.put(arr[right],hm.getOrDefault(arr[right],0)+1);
// 当有重复值时候,开始收缩
            while( hm.get(arr[right]) >1){
                hm.put(arr[left],hm.get(arr[left])-1);
                left++;
            }
            res = Math.max(res, right-left +1);
            right ++;
        }
        return res;
    }
}
全部评论

相关推荐

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