LeetCode:Set Matrix Zeroes

来源:互联网 发布:mac接外置光驱不能读取 编辑:程序博客网 时间:2024/06/06 00:09

推荐参照:Leetcode题目难度等级及面试频率总结

题目描述: 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. Did you use extra space?

  A straight forward solution using O(mn) 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?

思路一:

  因为set具有元素不重复的特性,用set来存储值0所在的行号和列号。然后将0所在的行全部置0,将0所在的列全部置0。

时间复杂度O(nm),空间复杂度O(m+n)

import java.util.*;public class Solution {    public void setZeroes(int[][] matrix) {        int m = matrix.length;        int n = matrix[0].length;        HashSet<Integer> setM = new HashSet<>();        HashSet<Integer> setN = new HashSet<>();        for (int i = 0; i < m; i++)            for (int j = 0; j < n; j++) {                if (matrix[i][j] == 0) {                    setM.add(i);                    setN.add(j);                }            }        // 将0所在的行全部置0        for (int row : setM)            for (int col = 0; col < n; col++)                matrix[row][col] = 0;        // 将0所在的列全部置0        for (int col : setN)            for (int row = 0; row < m; row++)                matrix[row][col] = 0;    }}

思路二:

  使用第一行第一列作为记录的存储空间,即从第二行第二列开始遍历,遇到0则将其所在行列的第一个元素置为0,需要注意的是记得判断存储原来第一行第一列是否为0。

时间复杂度O(mn),空间复杂度O(1)

public class Solution {    public void setZeroes(int[][] matrix) {        int m = matrix.length;        int n = matrix[0].length;        boolean firRow = false, firCol = false;        // 判断第一行第一列是否有0,防止被后面置0的操作覆盖        for (int j = 0; j < n; j++)            if (matrix[0][j] == 0) {                firRow = true;                break;            }        for (int i = 0; i < m; i++)            if (matrix[i][0] == 0) {                firCol = true;                break;            }        // 然后从第二行第二列开始遍历,遇到0则将其所在行列的第一个元素置为0.        for (int i = 1; i < m; i++)            for (int j = 1; j < n; j++) {                if (matrix[i][j] == 0) {                    matrix[i][0] = 0;                    matrix[0][j] = 0;                }            }        // 把第一列的0所在行都设为0,把第一行的0所在列都设为0        for (int i = 1; i < m; i++)            for (int j = 1; j < n; j++)                if (matrix[i][0] == 0 || matrix[0][j] == 0)                    matrix[i][j] = 0;        if (firRow) {            for (int i = 0; i < n; i++)                matrix[0][i] = 0;        }        if (firCol) {            for (int j = 0; j < m; j++)                matrix[j][0] = 0;        }    }}

—–乐于分享,共同进步
—–更多文章请看:http://blog.csdn.net/u011489043
—–Any comments greatly appreciated

0 0
原创粉丝点击