您的位置:首页 > 其它

清除行列

2016-04-09 22:21 162 查看


题目描述

请编写一个算法,若MxN矩阵中某个元素为0,则将其所在的行与列清零。

给定一个MxN的int[][]矩阵(C++中为vector<vector>)mat和矩阵的阶数n,请返回完成操作后的int[][]矩阵(C++中为vector<vector>),保证n小于等于300,矩阵中的元素为int范围内。
测试样例:
[[1,2,3],[0,1,2],[0,0,1]]


返回:[[0,0,3],[0,0,0],[0,0,0]]

import java.util.*;

public class Clearer {
public int[][] clearZero(int[][] mat, int n) {
// write code here
Set<Integer> rows = new HashSet<Integer>();
Set<Integer> cols = new HashSet<Integer>();
for(int i=0; i<n; ++i){
for(int j=0; j<n; ++j){
if(mat[i][j]==0){
rows.add(i);
cols.add(j);
}
}
}

for(Integer w : rows){
for(int j=0; j<n; ++j){
mat[w][j] = 0;
}
}

for(Integer w : cols){
for(int i=0; i<n; ++i){
mat[i][w] = 0;
}
}

return mat;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: