【LeetCode-面試演算法經典-Java實現】【070-Set Matrix Zeroes(矩陣置零)】

來源:互聯網
上載者:User

標籤:矩陣   演算法   面試   java   

【070-Set Matrix Zeroes(矩陣置零)】【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】原題

  Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

題目大意

  給定一個m*n的矩陣,如果某個位置是0。將對應的行和列設定為0。

解題思路

  先對矩陣進行掃描,標記要進行置0的行和列,對要進行置0的行在第0列上進行標記,對置0的列在第0行上進行標標記。同時還要兩變數記錄第0行和第0列是否要置0,最後進行置0操作。

代碼實現

演算法實作類別

public class Solution {    public void setZeroes(int[][] matrix) {        // 第一行被設定的標誌        boolean rowFlag = false;        // 第一列被設定的標誌        boolean colFlag = false;        for (int i = 0; i < matrix.length; i++) {            for (int j = 0; j < matrix[0].length; j++) {                if (matrix[i][j] == 0) {                    // 標記第一行要被設定                    if (i == 0) {                        rowFlag = true;                    }                    // 標記第一列要被設定                    if (j == 0){                        colFlag = true;                    }                    // 在行列在標記要設定為0的行和列                    matrix[0][j] = 0;                    matrix[i][0] = 0;                }            }        }        // 對第二行第二列開始的元素設定0        for (int i = 1; i < matrix.length; i++) {            for (int j = 1; j < matrix[0].length; j++) {                if (matrix[i][0] == 0 || matrix[0][j] == 0) {                    matrix[i][j] = 0;                }            }        }        // 設定第一行為0        if (rowFlag) {            for (int j = 0; j < matrix[0].length; j++) {                matrix[0][j] = 0;            }        }        // 設定第一列為0        if (colFlag) {            for (int i = 0; i < matrix.length; i++) {                matrix[i][0] = 0;            }        }    }}
評測結果

  點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。

特別說明歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47371979】

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

【LeetCode-面試演算法經典-Java實現】【070-Set Matrix Zeroes(矩陣置零)】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.