zoukankan      html  css  js  c++  java
  • leecode 73. 矩阵置零

    给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。

    进阶:

    • 一个直观的解决方案是使用  O(mn) 的额外空间,但这并不是一个好的解决方案。
    • 一个简单的改进方案是使用 O(m + n) 的额外空间,但这仍然不是最好的解决方案。
    • 你能想出一个仅使用常量空间的解决方案吗?

    示例 1:

     

    输入:matrix = [[1,1,1],[1,0,1],[1,1,1]]
    输出:[[1,0,1],[0,0,0],[1,0,1]]

    示例 2:

     

    输入:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
    输出:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]
    /*
     * 73. Set Matrix Zeroes
     * 题意:把含有0的行和列都设成0
     * 难度:Medium
     * 分类:Array
     * 思路:用第一行和第一列作为标志位。注意赋值的时候从后往前,防止标志位被改变
     *      两遍循环,先记录,再置位
     * Tips:注意赋值的顺序,防止标志位被改变
     *       思路是很简单,但有许多细节
     */
        public void setZeroes(int[][] matrix) {
            boolean col0 = false;   //因为 matrix[0][0] 只有一个位置,所以用一个变量单独记录
            for (int i = 0; i < matrix.length ; i++) {
                if(matrix[i][0]==0) col0 = true;
                for (int j = 1; j < matrix[0].length ; j++) {
                    if(matrix[i][j]==0){
                        matrix[i][0] = 0;
                        matrix[0][j] = 0;
                    }
                }
            }
            for (int i = matrix.length-1; i >= 0 ; i--) {   //从后往前,标志位那一行最后改变
                for (int j = matrix[0].length-1; j >= 1 ; j--) {    // j>=1 不包含j==0
                    if( matrix[i][0]==0 || matrix[0][j]==0 ) matrix[i][j] = 0;
                }
                if(col0==true) matrix[i][0]=0;  //要在for循环后,再把[i][0]改变
            }
        }
  • 相关阅读:
    基于摸板匹配的目標跟蹤算法
    spoj 2713 Can you answer these queries IV
    zoj 3633 Alice's present
    hdu 3642 Get The Treasury
    poj 1195 Mobile phones
    poj 2760 End of Windless Days
    zoj 3540 Adding New Machine
    spoj 1716 Can you answer these queries III
    spoj 1043 Can you answer these queries I
    spoj 2916 Can you answer these queries V
  • 原文地址:https://www.cnblogs.com/kpwong/p/14651503.html
Copyright © 2011-2022 走看看