1.7
来源:互联网 发布:win7怎么查看网络凭据 编辑:程序博客网 时间:2024/04/29 14:31
Topic: Write an algorithm such that if an element in an M*N matrix is 0, its entire row and column are set to 0.
// 注意点1:不能看到一个0,马上把那一行那一列都设为0,这样遍历的话,整个矩阵会全为0.
// 方法1:第一次遍历找到0的位置,标记在新开的matrix里;第二次遍历置0 (do a second pass). Space:O(M*N)
// 方法2:第一次遍历找到0的位置,把行号和列号标记在两个boolean array里;第二次遍历置0.
// 方法3:To make more efficient, use a bit vector instead of a Boolean array.
public class CC1_1 {public static void SetZero(int [][] matrix){ boolean[] row = new boolean[matrix.length]; boolean[] column = new boolean[matrix[0].length]; for( int i = 0; i <matrix.length; i++ ){ for( int j = 0; j < matrix[0].length; j++ ){ if( matrix[i][j] == 0 ){ row[i] = true; column[j] = true; } } } for( int i = 0; i < matrix.length; i++ ){ for(int j=0; j<matrix[0].length;j++){ if(row[i]||column[j]) matrix[i][j] = 0; } } }public static void print(int[][] matrix) {int n = matrix.length;for(int i = 0; i < n; i++) {for(int j = 0; j < n; j++) {System.out.print(matrix[i][j]);System.out.print(' ');}System.out.println();}}public static void main(String[] args) {int[][] matrix = {{1, 2, 3, 4},{5, 0, 7, 8},{9, 10, 0, 12},{13, 14, 15, 16}};SetZero(matrix);print(matrix);}}
//结果1 0 0 4 0 0 0 0 0 0 0 0 13 0 0 16
- 1.7
- 1.7
- 1.7
- 1.7
- 1.7
- 1.7
- 1.7
- 1.7
- 1.7~1.8
- ed 1.7
- OfficeMenu 1.7
- JDK 1.7
- 1.7 小结
- Java 1.7
- hdu1.1.7
- hdu2.1.7
- ACM1.1.7
- CareerCup 1.7
- 面试题之树的高度分析
- 关于JDK的新看法
- Qt程序打包成exe可执行文件图文教程
- C/C++/C#面试题精选(1)
- libvlc外部api的简单整理
- 1.7
- 连续性分组连接技术
- Visual C++ 6.0点击go to definition提示the symbol "XX" is undefined
- OpenGL的视图和模型变换
- 织梦本地服务器环境搭建
- 2013年9月1日、Come On|Maven初步认识
- Linux shell 脚本实例
- centos5镜像下载
- 【转载】字符串匹配的Boyer-Moore算法