Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
[分析]
错误思路:第一遍扫描矩阵,遇到0时将其所在行和列非0元素标记为一个特殊符号。第二遍扫描,将所有特殊符号置0。但因为矩阵元素是整数,找不到不能用整数表示的特殊符号,总有case过不了。
正确的思路是使用两个数组在扫描数组过程中分别存储各行各列是否需要被清零的判断,优化的实现是使用输入矩阵的第一行和第一列进行存储,让matrix[0][0]代表第一行的情况,则还需另一个变量col0存放第一列的状态。第一遍扫描是top-down style,第二遍清零时采用bottom-up style可以让代码更简洁。
[ref]
https://leetcode.com/discuss/15997/any-shortest-o-1-space-solution
解析得比较清楚
http://blog.csdn.net/linhuanmars/article/details/24066199
[url]
public class Solution {
public void setZeroes(int[][] matrix) {
if (matrix == null)
return;
int rows = matrix.length, cols = matrix[0].length;
int col0 = -1;
for (int i = 0; i < rows; i++) {
if (matrix[i][0] == 0)
col0 = 0;
for (int j = 1; j < cols; j++) {
if (matrix[i][j] == 0)
matrix[i][0] = matrix[0][j] = 0;
}
}
for (int i = rows - 1; i >= 0; i--) {
for (int j = cols - 1; j >= 1; j--) {
if (matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
}
if (col0 == 0)
matrix[i][0] = 0;
}
}
}
[/url]
分享到:
相关推荐
《leetcode-solutions》,刷算法题,需要有一定的英文阅读能力。。。
IDEA 插件,lettcode刷题,leetcode-editor7.4版本下载进行本地导入(直接将压缩包拖进IDEA即可)
Algorithm-LeetCode-Sol-Res.zip,干净,易懂的解决方案和资源,为leetcode在线判断算法问题。,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。
Algorithm-leetcode-spider.zip,leetcode公司,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。
leetcode-cli-plugins leetcode-cli 的第 3 方插件。 什么是 如何使用 如何使用 插件 名称 描述 增强的命令 按公司或标签过滤问题 list 不要在同一台计算机上使 Chrome 的会话过期 login 不要在同一台计算机上使 ...
在IDE中解决LeetCode问题,支持leetcode.com与leetcode-cn.com,满足基本的做题需求。 理论上支持: IntelliJ IDEA PhpStorm WebStorm PyCharm RubyMine AppCode CLion GoLand DataGrip Rider MPS Android Studio。
解题思路思路和LeetCode-python 503.下一个更大元素 II一致,只是这里求的是下标的距离,而不是数值倒序搜索,用到栈,栈里存储索引情况1:若栈为
leetcode-cheat 的发布 它是什么 ? 这是一个chrome 扩展,可以帮助您更高效地使用 leetcode。您可以从 重要: leetcode-cheat 现在只支持中文版。 也就是说不完全支持leetcode.com,但是你可以用leetcode-cn.com代替...
leetcode 答案解析 golang解答
~/.vscode/extensions/leetcode.vscode-leetcode-0.17.0/node_modules/vsc-leetcode-cli/bin/leetcode /usr/local/bin/leetcode 修改模板 open ~/.vscode/extensions/leetcode.vscode-leetcode-0.17.0/node_modules/...
leetcode-editor,在ide中做leetcode练习,支持leetcode.com和leetcode-cn.com,以满足练习的基本需求。理论上支持:intellij idea phpstorm webstorm pycharm rubymine appcode clion goland datagrip rider mps ...
leetcode-helper-1.7.1
然后进入到LeetCode-Spider目录中修改config.json,其中outputDir需要填写该工程的/docs/views文件夹路径 { "username": "aaa", "password": "bbb", "outputDir": "/Users/liuyao/Downloads/LeetCode-Blog-Test/docs...
leetcode-tag-dynamic programming
leetcode-cli 注意:这个存储库是为了临时使用而分叉的。 注意:从 webbrowser 复制 cookie 并使用leetcode user -c可以临时修复不能。 一个享受 leetcode 的高效 cli 工具! 非常感谢 leetcode.com,一个非常棒的...
leetcode-tag-Tree
leetcode-tag-Stack
leetcode-tag-array
Algorithm-LeetCode-Solution-From-GuaZiDou.zip,Leetcode解决方案Gitbook,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。