题解 | #最长无重复子数组#
最长无重复子数组
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;
}
}
查看3道真题和解析