Leetcode刷題記—— 73. Set Matrix Zeroes(設定矩陣0)
阿新 • • 發佈:2019-02-19
一、題目敘述:
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
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); } }