29. 顺时针打印矩阵
思路:https://www.bilibili.com/vide...
代码
public int[] spiralOrder(int[][] matrix) { int row = matrix.length; if (row==0){ int[] ints = new int[row]; return ints; } int col = matrix[0].length; int[] mat = new int[row*col]; boolean b = false; int count =0; int r1 = 0; int r2 = row; int c1 = 0; int c2 = col; while(count!=row*col){ for (int i = c1; i < c2; i++) { mat[count++] = matrix[r1][i]; if(count==row*col) { b = true; break; } } if (b == true) break; for (int i = r1+1; i < r2; i++) { mat[count++] = matrix[i][c2-1]; if(count==row*col) { b = true; break; } } if (b == true) break; for (int i = c2-2; i >= c1; i--) { mat[count++] = matrix[r2-1][i]; if(count==row*col) { b = true; break; } } if (b == true) break; for (int i = r2-2; i >= r1+1; i--) { mat[count++] = matrix[i][c1]; if(count==row*col) { b = true; break; } } if (b == true) break; r1++; r2--; c1++; c2--; } return mat; }
30. 蕴含min函数的栈
思路:辅助栈中始终放以后最小元素,
,https://www.bilibili.com/vide...
代码
重点:
也能够:
class MinStack { Deque<Integer> A; Deque<Integer> B; public MinStack() { A = new LinkedList<>(); B = new LinkedList<>(); } public void push(int x) { if (A.isEmpty()){ A.push(x); B.push(x); return; } if (x<B.peek()){ A.push(x); B.push(x); return; } A.push(x); B.push(B.peek()); } public void pop() { A.pop(); B.pop(); } public int top() { return A.peek(); } public int min() { return B.peek(); }}
Java Deque接口 应用办法(栈、队列、双端队列)
31. 栈的压入、弹出序列
思路:https://www.bilibili.com/vide...
始终push,while有雷同的pop走,没有了又持续push
public boolean validateStackSequences(int[] pushed, int[] popped) { Deque<Integer> ss = new LinkedList<Integer>(); if (pushed.length != popped.length) return false; int K = 0; for (int i = 0; i < pushed.length; i++) { ss.push(pushed[i]); while(!ss.isEmpty()&&ss.peek()==popped[K]){ ss.pop(); K++; if (K==pushed.length) return true; } } return ss.isEmpty(); }