题解 | #最长无重复子数组#
最长无重复子数组
http://www.nowcoder.com/practice/b56799ebfd684fb394bd315e89324fb4
- 思维不要固化,map键对(arr[i],i),key和value何尝不能互换。
- containsKey(key)看是否包含某个key值
- map的get是get value值而不是key
import java.util.*;
public class Solution {
/**
*
* @param arr int整型一维数组 the array
* @return int整型
*/
public int maxLength (int[] arr) {
// write code here
if(arr.length == 0)
return 0;
HashMap<Integer,Integer> map = new HashMap<>();
int max = 0;
for(int i=0,j=0;i<arr.length;++i){
if(map.containsKey(arr[i])){
j = Math.max(j,map.get(arr[i])+1);
}
map.put(arr[i],i);
max = Math.max(max,i-j+1);
}
return max;
}
}