Leetcode刷题记—— 73. Set Matrix Zeroes(设置矩阵0)

来源:互联网 发布:前端ajax请求php文件 编辑:程序博客网 时间:2024/05/22 12:46

一、题目叙述:

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.

Subscribe to see which companies asked this question.

给定一个m*n的矩阵,遇到为0的元素,将其所在行和列的元素都设为0.

二、解题思路:

Medium题。我看了下,我得进步呀!!!每次一看通过的代码只优于百分之0.几的人,我真是晕。

思路:

(1)直接了当的思路,碰到0元素,记下其行号列号。

(2)循环为这些行这些列的元素赋值为0。

(3)注意矩阵为空。

三、源码:

import java.util.ArrayList;import java.util.Arrays;public class Solution  {  public void setZeroes(int[][] matrix) {  if (matrix == null) return;      ArrayList<Integer> x = new ArrayList<Integer>();      ArrayList<Integer> y = new ArrayList<Integer>();      for (int i = 0; i < matrix.length; i++)      for (int j = 0; j < matrix[0].length; j++)      {      if (matrix[i][j] == 0)       {      x.add(i);      y.add(j);      }            }      for (int i = 0; i < matrix[0].length; i++)      {       for (int sx : x )       matrix[sx][i] = 0;      }      for (int j = 0; j < matrix.length; j++)      {      for (int sy : y)      matrix[j][sy] = 0;      }      System.out.println(Arrays.deepToString(matrix));       return;    }    public static void main(String args[])          {                           int[][] board = {{1,2,3},{4,0,5}};     //String word = "ABfS";        Solution solution = new Solution();             solution.setZeroes(board);     }      }  


0 0