码迷,mamicode.com
首页 > 其他好文 > 详细

55. Set Matrix Zeroes

时间:2014-09-03 19:45:37      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   strong   ar   for   div   sp   

Set Matrix Zeroes

(Link: https://oj.leetcode.com/problems/set-matrix-zeroes/)

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 元素,分别将其投影在记下的行和列上(做标记)。遍历之后,对于所有行中的标记,将其所在列都置为 0; 对于所有列中标记,将其所在行都置为 0. (最后置标记的行和列为 0. 可含在上述步骤) 时间: O(n2), 空间 : O(1)

class Solution {
public:
	void setZeroes(vector<vector<int> > &matrix) {
		if(!matrix.size() || !matrix[0].size()) return;
		const int INF = 1001;
		int row = matrix.size(), col = matrix[0].size();
		int u = -1, v = -1;
		for(int r = 0; r < row; ++r) 
			for(int c = 0; c < col; ++c) {
				if(matrix[r][c] == 0) {
					if(u == -1) {  u = r, v = c; continue; }
					matrix[u][c] = INF;
					matrix[r][v] = INF;
				}
			}
			if(u == -1) return;
			if(matrix[u][v] == INF) matrix[u][v] = 0;
			for(int c = 0; c < col; ++c) {
				if(matrix[u][c] == INF) {
					for(int i = 0; i < row; ++i)  matrix[i][c] = 0;
				} else matrix[u][c] = 0;
			}
			for(int r = 0; r < row; ++r) {
				if(matrix[r][v] == INF) {
					for(int j = 0; j < col; ++j) matrix[r][j] = 0;
				} else matrix[r][v] = 0;
			}
	}
};

 

 

55. Set Matrix Zeroes

标签:style   blog   http   io   strong   ar   for   div   sp   

原文地址:http://www.cnblogs.com/liyangguang1988/p/3954325.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!