看了大佬们的思路才写出来的,太笨了,发现自己双指针的就不知道咋动手。一般简单的遍历写不出时,应当考虑使用集合,队列这种额外空间帮助求解的。
1.利用双指针
利用双指针,一左一右指针,两者一开始都在开头,从头开始遍历,利用哈希表记录数组的数字跟位置,遍历时哈希表中若存在,就需要更新左指针,最后再比较窗口大小与当前最大值。时间复杂度为O(n),一个循环,空间复杂度O(n),一个HashMap的长度;
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;
Map<Integer,Integer> map=new HashMap<>();
int left=0;//左指针
int max=0;
for(int right=0;right<arr.length;right++){
if(map.containsKey(arr[right])){//存在相同数字
left=Math.max(map.get(arr[right])+1,left);//更新左指针
}
map.put(arr[right],right);
max=Math.max(max,right-left+1);//比较最大值与当前窗口的长度大小,取较大值
}
return max;
}
}
2.利用队列
利用队列(先进先出),遍历数组,需要再一次循环,如果遇到相同的数字,就将队头出队,最后队列存在数字,即为一个子数组,比较每一个子数组的长度。时间复杂度O(n2),两次循环,空间复杂度:O(n)一个队列的长度。队列其实也可以换成集合写也可以。
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;
int max=0;//记录结果
Queue<integer> queue=new LinkedList<>();
for(int i:arr){
while(queue.contains(i)){//存在相同数字,出队
queue.poll();
}
queue.offer(i);//入队
max=Math.max(max,queue.size());
}
return max;
}
}
3.</integer>