Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- expo
- JavaScript
- callbackhell
- Promise
- arguments
- await
- 변수
- 유사배열객체
- 플러스친구
- 챗봇
- vuejs
- 자연어처리
- 자바스크립트
- callback
- async
- trim
- closure
- ReactNative
- 함수
- 오픈빌더
- 카카오
- 객체
- 카카오톡채널
- es6
- 배열
- 오픈채팅
- 콜백함수
- developers
- es7
- 순수함수
Archives
- Today
- Total
말랑말랑 LAB
leetcode#73 Set Matrix Zeroes 본문
Question
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?
solution
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var setZeroes = function(matrix) {
var result = matrix.map(v => v.slice());
var row = matrix.length;
var col = matrix[0].length;
var [targetRow, targetCol] = [0, 0];
for(var i=0; i<row; i++) {
for(var j=0; j<col; j++) {
if (matrix[i][j] === 0) {
targetRow = i;
targetCol = j;
var tRow = targetRow + 1;
while(tRow >= 0 && tRow < row) {
if (result[tRow][targetCol] !== 0) {
result[tRow][targetCol] = 0;
}
tRow++;
}
var tRow = targetRow - 1;
while(tRow >= 0 && tRow < row) {
if (result[tRow][targetCol] !== 0) {
result[tRow][targetCol] = 0;
}
tRow--;
}
var tCol = targetCol + 1;
while(tCol >= 0 && tCol < col) {
if (result[targetRow][tCol] !== 0) {
result[targetRow][tCol] = 0;
}
tCol++;
}
var tCol = targetCol - 1;
while(tCol >= 0 && tCol < col) {
if (result[targetRow][tCol] !== 0) {
result[targetRow][tCol] = 0;
}
tCol--;
}
}
}
}
matrix = result;
};
'JavaScript > Algorithm' 카테고리의 다른 글
leetcode#2 Add Two Numbers (0) | 2021.08.21 |
---|---|
[프로그래머스 알고리즘] Level 2 124 나라의 숫자 (0) | 2018.12.28 |
[프로그래머스 알고리즘] Level 1 수박수박수박 문제 (0) | 2018.12.16 |
Comments