单调队列解决滑动窗口问题(单调队列由大到小,加入之前把前面比它小的元素都从右端排出,最左端的元素最大
才记录答案,
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int[] res=new int[nums.length-k+1];
Deque<Integer> q=new LinkedList<>();
int index=0;
for(int i=0;i<nums.length;i++){
//入,要存入索引 不然不好知道是否该出窗口了
while(!q.isEmpty()&&nums[i]>=nums[q.getLast()]){
q.removeLast();
}
q.add(i);
//出,判断元素是否还在窗口内
if(i-q.getFirst()>=k){
q.removeFirst();
}
if(i>=k-1){
res[index++]=nums[q.getFirst()];
}
}
return res;
}
}
图的遍历
class Solution {
List<List<Integer>> res=new LinkedList<>();
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
LinkedList<Integer> path=new LinkedList<>();
traver(graph,0,path);
return res;
}
void traver(int[][] graph,int s,LinkedList<Integer> path){
path.add(s);
if(s==graph.length-1){
res.add(new LinkedList<>(path));
}
for(int x: graph[s]){
traver(graph,x,path);
}
path.removeLast();
}
}