zoukankan      html  css  js  c++  java
  • set-matrix-zeroes


    /**
    * Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
    * click to show follow up.
    * Follow up:
    * Did you use extra space?
    * A straight forward solution using O(m n) space is probably a bad idea.
    * A simple improvement uses O(m + n) space, but still not the best solution.
    * Could you devise a constant space solution?
    *
    * 给定m x n矩阵,如果元素为0,则将其整行和整列设置为0。就位。
    * 单击以显示“跟进”。
    * 跟进:
    * 你用了额外的空间吗?
    * 使用O(M N)空间的直接解决方案可能是一个坏主意。
    * 一个简单的改进使用O(M+N)空间,但仍然不是最好的解决方案。
    * 你能想出一个常数空间解吗?
    */
    import java.util.ArrayList;
    
    /**
     * Given a m x n matrix, if an element is 0, set its entire row and column to 0.   Do it in place.
     * click to show follow up.
     * Follow up:
     * Did you use extra space?
     * A straight forward solution using O(m n) space is probably a bad idea.
     * A simple improvement uses O(m + n) space, but still not the best solution.
     * Could you devise a constant space solution?
     *
     * 给定m x n矩阵,如果元素为0,则将其整行和整列设置为0。就位。
     * 单击以显示“跟进”。
     * 跟进:
     * 你用了额外的空间吗?
     * 使用O(M N)空间的直接解决方案可能是一个坏主意。
     * 一个简单的改进使用O(M+N)空间,但仍然不是最好的解决方案。
     * 你能想出一个常数空间解吗?
     */
    
    public class Main36 {
        public static void main(String[] args) {
            int[][] matrix = {
                    {1,2,3,4,0},
                    {6,0,8,9,10},
                    {11,12,0,14,15},
                    {16,17,18,19,20}
            };
            setZeroes(matrix);
            for (int i=0;i<matrix.length;i++) {
                for (int j=0;j<matrix[i].length;j++) {
                    System.out.print(matrix[i][j] + ", ");
                }
                System.out.println("");
            }
        }
    
        public static void setZeroes(int[][] matrix) {
            ArrayList<Integer> row = new ArrayList<>();
            ArrayList<Integer> colum = new ArrayList<>();
            for (int i=0;i<matrix.length;i++) {
                for (int j=0;j<matrix[i].length;j++) {
                    if (matrix[i][j] == 0) {
                        row.add(i);
                        colum.add(j);
                    }
                }
            }
            for (Integer e : row){
                for (int i=0;i<matrix[e].length;i++) {
                    matrix[e][i] = 0;
                }
            }
            for (Integer e : colum) {
                for (int j=0;j<matrix.length;j++) {
                    matrix[j][e] = 0;
                }
            }
    
        }
    }
    

      

  • 相关阅读:
    Homework template (latex)
    Basic skill of searching
    国庆第三次集训: 2012 ACM-ICPC Asia Regional Contest Chengdu Site
    新学期随笔
    暑期集训感想
    暑期集训 DP 篇
    POJ 1195 Mobile Phones 二维树状数组
    51Nod1246 罐子和硬币,不能均分的题
    一维战舰,一道考区间的好题
    51NOD 1268 和为K的组合 搜索水题
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11313652.html
Copyright © 2011-2022 走看看