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

最长无重复子数组

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 int length = arr.length; if(length==0 || length==1){ return length; }

    HashMap<Integer,Integer> hashMap = new HashMap<>();
    int first = 0;
    int count = 0;
    int maxLen = 1;
    boolean flag = true;
    for(int i=0;i<length;i++){
        if(hashMap.containsKey(arr[i])){//当前数据已存在
            first = Math.min(hashMap.get(arr[i]),first);
            count = i - first;
            first = hashMap.get(arr[i])+1;
            
            flag = false;
            
            if(count>maxLen){
                maxLen = count;
            }
            if(arr[i-1] == arr[i]){
                hashMap.clear();
            }
            hashMap.put(arr[i],i);
        }else{//当前数据还没有存在
            hashMap.put(arr[i],i);
            if(i==length-1){
                flag = true;
            }
        }
    }
    
    int lastLen = length-first;
    if(flag && lastLen>maxLen){
        maxLen = lastLen;
    }
    return maxLen;
}

}

全部评论

相关推荐

牛客42327521...:在你没来公司之前你们公司连登录功能都没做?让一个实习生做登录页面?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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