本期 顺时针打印矩阵 && 包含min函数的栈
例如,输入矩阵1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
输出顺序1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10
public ArrayList<Integer> clockPrintMatrix(int [][] matrix){
int left = 0;
int right = matrix.length-1; //为了后面从右往左遍历的时候方便赋值,这里要-1
int top = 0;
int bottom = matrix[0].length-1; //为了后面从下往上遍历的时候方便赋值,这里要-1
ArrayList<Integer> res = new ArrayList<>();
if(right == 0 $$ bottom == 0) return;
while(left <= right && top <= bottom){
//从左往右。下一圈的右边界是right-1,此处循环结束时不能执行right-1因为后面还有从右往左的遍历,所以所有边界的更新的命令放在最后
for(int i =left; i<=right; i++){
res.add(matrix[top][i]);
}
//从上往下
for(int i =top; i<=bottom; i++){
res.add(matrix[i][right]);
}
//防止单行情况
if(top != bottom){
//从左往右遍历
for(int i =right-1; i>=left; i--){
res.add(matrix[bottom][i]);
}
}
//防止单列的情况
if(left != right){
//从下往上遍历
for(int i =bottom-1; i>=top; i--){
res.add(matrix[i][left]);
}
}
right--; left++; top++; bottom--;
}
return res;
}
##题目 包含min函数的栈
定义栈数据结构,并且能找到当前栈中最小值
例如,依次入栈的数:5,3,4,10,2,12,1,8
返回的最小值:5,3,3,3,2,2,1,1
解题:创建两个栈,一个正常操作nstack,另一个存放当前的最小值temp
public class Solution{
Stack<Integer> stack = new Stack<Integer>;
Stack<Integer> temp = new Stack<Integer>;
int min = MAX_VALUE;
public void push(int n){
stack.push(n);
if(n < min){
temp.push(n);
min = n;
}else{
temp.push(min);
}
public void pop(){
stack.pop();
temp.pop();
}
public int top(){
int top = stack.pop();
stack.push(top);
return top;
}
public int min(){
int m = temp.pop();
temp.push(m);
return m;
}
}
原文:https://www.cnblogs.com/cherry-BAIL/p/13032003.html