首页 > 其他 > 详细

剑指offer(9)

时间:2020-06-03 23:38:34      阅读:87      评论:0      收藏:0      [点我收藏+]

本期 顺时针打印矩阵 && 包含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;

 }

}

剑指offer(9)

原文:https://www.cnblogs.com/cherry-BAIL/p/13032003.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!