Cracking coding interview(1.7) 设置某个位置为零的矩阵对应行列均为0

1.7 Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.


import java.util.ArrayList;

public class Solution{
	//time complexity:O(m*n), space complexity:O(m+n)(worst complexity)
	public static void setMatrix(int[][] M){
		int[] c = new int[M.length];//
		//record row or col need to be set with 0
		//space complexty:O(m+n)
		ArrayList<Integer> row = new ArrayList<Integer>();
		ArrayList<Integer> col = new ArrayList<Integer>();
		//time complexity:O(m*n)
		for(int i=0;i < M.length;i++)
			for(int j=0;j < M[i].length;j++){
				if(M[i][j] != 0)
					continue;
				if(!row.contains(i))
					row.add(i);
				if(!col.contains(j))
					col.add(j);
			}
		//time complexity:O(m*n)
		//set row with 0
		int index = 0;
		for(int i=0;i < row.size();i++){
			index = row.get(i);
			for(int j=0;j < M[index].length;j++)
				M[index][j] = 0;
		}
		//time complexity:O(n*m)
		//set column with 0
		for(int i=0;i < col.size();i++){
			index = col.get(i);
			for(int j=0;j < M.length;j++)
				M[j][index] = 0;
		}
						
	}
	private static void printM(int[][] M){
		for(int i=0;i < M.length;i++){
			for(int j=0;j < M[i].length;j++)
				System.out.print(M[i][j]+" ");
			System.out.println();
		}
	}
	public static void main(String[] args){
		int[][] M = new int[][]{
			{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
			{1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
			{1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
			{1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
			{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
			{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
			{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
		};
		
		Solution.printM(M);
		Solution.setMatrix(M);
		System.out.println();//
		Solution.printM(M);
	}
}

当前较优解

最坏情况下:
时间复杂度:O(m*n)

空间复杂度:O(m+n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值