程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode | Set Matrix Zeroes

LeetCode | Set Matrix Zeroes

編輯:C++入門知識

題目

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.

Follow up:

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?

分析

題目要求使用常數的額外空間,因此需要借助矩陣本身的空間來輔助存儲,這裡借用了矩陣的第一行和第一列來輔助紀錄該行或該列是否為0.由於第一行第一列自身發生了改變,再用兩個布爾變量紀錄第一行和第一列是否為0即可。

代碼

public class SetMatrixZeroes {
	public void setZeroes(int[][] matrix) {
		if (matrix == null || matrix.length == 0) {
			return;
		}
		int M = matrix.length;
		int N = matrix[0].length;
		boolean isFirstRowZero = false;
		boolean isFirstColumnZero = false;
		for (int j = 0; j < N; ++j) {
			if (matrix[0][j] == 0) {
				isFirstRowZero = true;
				break;
			}
		}
		for (int i = 0; i < M; ++i) {
			if (matrix[i][0] == 0) {
				isFirstColumnZero = true;
				break;
			}
		}
		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;
				}
			}
		}

		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 (isFirstRowZero) {
			for (int j = 0; j < N; ++j) {
				matrix[0][j] = 0;
			}
		}

		if (isFirstColumnZero) {
			for (int i = 0; i < M; ++i) {
				matrix[i][0] = 0;
			}
		}
	}
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved