zoukankan      html  css  js  c++  java
  • 牛客_剑指offer题集——顺时针打印算法(java实现)

    题目链接:

    https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a?tpId=13&tqId=11172&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

    思路:

    想想矩阵的四周有四堵墙,每读完一层,相应的墙就加一,然后代码实现就好

    需要注意的点:极端情况需要另作考虑

    算法源码:

    package niuke;
    
    import java.util.ArrayList;
    
    public class 顺时针打印矩阵 {
        public static ArrayList<Integer> printMatrix(int [][] matrix) {
            ArrayList<Integer> res = new ArrayList<>();
    
            int length_top = matrix.length;
    
            int width_right = matrix[0].length;
            if(length_top == 1&&width_right==1){
                res.add(matrix[0][0]);
                return res;
            }
            int top =0;
            int right = width_right-1;
            int bottom = length_top-1;
            int left = 0;
            while(left<=right&&top<=bottom){
                for(int i = left;i<=right;++i){
                    res.add(matrix[top][i]);
                }
                top++;
                for(int i = top;i<=bottom;++i){
                    res.add(matrix[i][right]);
                }
                right--;
                if(top<=bottom)
                    for(int i = right;i>=left;--i){
                        res.add(matrix[bottom][i]);
                    }
                bottom--;
                if(left<=right)
                    for(int i = bottom;i>=top;--i){
                        res.add(matrix[i][left]);
                    }
                left++;
            }
    //        if(matrix.length%2==1){
    //            res.add(matrix[(matrix.length-1)/2][(matrix.length-1)/2]);
    //        }
            return res;
        }
    
        public static void main(String[] args) {
            int n =1;
            int[][] test = new int[5][5];
            for(int i = 0;i<5;++i){
                for(int j = 0;j<5;++j){
                    test[i][j] = n++;
                }
            }
            int[][] test2 = {{1},{2},{3},{4},{5}};
            int[][] test3 = {{1,2,3,4,5},{1,2,3,4,5}};
            ArrayList<Integer> res = printMatrix(test3);
            for(Integer each:res){
                System.out.println(each);
            }
        }
    }

    代码已经ac

    希望对大家有所帮助

    以上

  • 相关阅读:
    JQuery hover鼠标变换
    装饰者模式
    principle04
    Method Injection
    观察者模式
    Java SPI
    Redis--学习01
    OO设计中5大原则
    knowledge
    策略模式
  • 原文地址:https://www.cnblogs.com/lavender-pansy/p/12438748.html
Copyright © 2011-2022 走看看