• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
长发不及肩
博客园    首页    新随笔    联系   管理    订阅  订阅
剑指offer(9)

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

 }

}

posted on 2020-06-03 23:12  长发不及肩  阅读(130)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3