题号:73 标题:Set Matrix Zeroes 难度:Medium
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's, and return the matrix.
You must do it in place.
Example 1:
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Example 2:
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
Constraints:
• m == matrix.length
• n == matrix[0].length
• 1 <= m, n <= 200
• -231 <= matrix[i][j] <= 231 - 1
Follow up:
• A straightforward 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?
我的程序码
class Solution {
public void setZeroes(int[][] matrix) {
int i,j=0,k=0,size=(2*matrix[0].length*matrix.length) ;
int[] temp = new int[size];
Arrays.fill(temp, -1);
for(i=0;i<matrix.length;i++){
for(j=0;j<matrix[0].length;j++){
if(matrix[i][j]==0){
temp[k] = i;
temp[k+1]=j;
k=k+2;
}
}
}
for(i=0;i<size;i=i+2){
if(temp[i]<0){
break;
}else{
for(j=0;j<matrix[0].length;j++){
matrix[temp[i]][j] = 0;
}
for(j=0;j<matrix.length;j++){
matrix[j][temp[i+1]] = 0;
}
}
}
}
}
思考逻辑
本来以为只有0跟1想说先把要改成0的行跟列全部先存2,这样就不会因为後面还有0出现而影响判断,但後来发现阵列中的每个值可以是整数的整个范围,因此作罢。
但偷懒如我,又想到in-place,代表可以宣告一维,於是宣告一个可以储存mn2大小的一维,扫到0的座标存起来,两两一组,最後再把一维阵列中的座标对应的行跟列转成0就完成拉
day28心得
原本以为我这个宣告一个阵列是做坏事,但我看解答逻辑也差不多嘛,心安理得了!
tags: Vue.js ItIron2020 前言 昨天我们完成了专案的基本建置并建立一个简单的c...
总结来说this就像是没什麽太大的意义对於function而言,因为不管function的this他...
敝人很常踩到诈骗网站,第一屏就是一个庆祝的小动画, 恭喜我中奖(好想中威力彩啊) 网页也很常有这种奖...
人生真的很奇妙 可能在某个时间轴曾经跟某个人的时间轴交错 但当下是不认识的 然後在几年过後又再次交...
其实这里的翻译常常被顾问跟客户弄混~ 即使中文版的标准是翻成密码,但其实原文是加密(Encrypti...