[leetcode]73. Set Matrix Zeroes(Java)

本文介绍了一种高效的算法来实现矩阵中若某个元素为0,则将其所在行和列的所有元素都设置为0的操作,并提供了两种不同的解决方案,一种使用额外的数据结构,另一种通过标记行列的方式进行原地操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://leetcode.com/problems/set-matrix-zeroes/#/description


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.


package go.jacob.day628;

import java.util.HashSet;

public class Demo3 {
	/*
	 * Runtime: 2 ms.Your runtime beats 27.13 % of java submissions.
	 */
	public void setZeroes(int[][] matrix) {
		//fr和fc用来记录第一行和第一列是否要置0
		boolean fr = false, fc = false;
		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix[0].length; j++) {
				//如果[i,j]为0,把该元素所在的行列头元素设为0
				if (matrix[i][j] == 0) {
					if (i == 0)
						fr = true;
					if (j == 0)
						fc = true;
					matrix[0][j] = 0;
					matrix[i][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;
				}
			}
		}
		//判断,将首行首列置为零
		if (fr) {
			for (int j = 0; j < matrix[0].length; j++) {
				matrix[0][j] = 0;
			}
		}
		if (fc) {
			for (int i = 0; i < matrix.length; i++) {
				matrix[i][0] = 0;
			}
		}
	}

	/*
	 * Solution by me.
	 */
	public void setZeroes_1(int[][] matrix) {
		if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
			return;
		int m = matrix.length;
		int n = matrix[0].length;

		HashSet<Integer> rows = new HashSet<Integer>();
		HashSet<Integer> cols = new HashSet<Integer>();

		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				if (rows.contains(i) && cols.contains(j))
					continue;
				if (matrix[i][j] == 0) {
					rows.add(i);
					cols.add(j);
				}
			}
		}

		for (int i : rows) {
			for (int j = 0; j < n; j++) {
				matrix[i][j] = 0;
			}
		}

		for (int i : cols) {
			for (int j = 0; j < m; j++) {
				matrix[j][i] = 0;
			}
		}

	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值