본문 바로가기

LeetCode

3033. Modify the Matrix / TypeScript

Given a 0-indexed m x n integer matrix matrix, create a new 0-indexed matrix called answer. Make answer equal to matrix, then replace each element with the value -1 with the maximum element in its respective column.

Return the matrix answer.

 

Example 1:

Input: matrix = [[1,2,-1],[4,-1,6],[7,8,9]]
Output: [[1,2,9],[4,8,6],[7,8,9]]
Explanation: The diagram above shows the elements that are changed (in blue).
- We replace the value in the cell [1][1] with the maximum value in the column 1, that is 8.
- We replace the value in the cell [0][2] with the maximum value in the column 2, that is 9.

Example 2:

Input: matrix = [[3,-1],[5,2]]
Output: [[3,2],[5,2]]
Explanation: The diagram above shows the elements that are changed (in blue).

 

 

풀이

 

function modifiedMatrix(matrix: number[][]): number[][] {
    const columns: number[][] = Array.from({ length: matrix[0].length }, () => [])
    for (const row of matrix) {
        row.forEach((val, colIndex) => {
            columns[colIndex].push(val)
        })
    }
    return matrix.map((row) => row.map((val, colIndex) => {
        if (val == -1) {
            return Math.max(...columns[colIndex])
        }
        return val
    })
    )
};

 

 

    row.forEach((val, colIndex) => {
            columns[colIndex].push(val)
        })

 

 

  • val: row 배열의 현재 요소 값.
  • colIndex: 현재 요소의 인덱스.
  • columns[colIndex].push(val): columns 배열의 colIndex 번째 배열에 val 값을 추가.

 

[
    [1, -1, 3],
    [4, 5, -1],
    [-1, 8, 9]
]

 

 

  1. 첫 번째 행 [1, -1, 3]에 대해:
    • val = 1, colIndex = 0 → columns[0].push(1) → columns는 [[1], [], []]
    • val = -1, colIndex = 1 → columns[1].push(-1) → columns는 [[1], [-1], []]
    • val = 3, colIndex = 2 → columns[2].push(3) → columns는 [[1], [-1], [3]]
  2. 두 번째 행 [4, 5, -1]에 대해:
    • val = 4, colIndex = 0 → columns[0].push(4) → columns는 [[1, 4], [-1], [3]]
    • val = 5, colIndex = 1 → columns[1].push(5) → columns는 [[1, 4], [-1, 5], [3]]
    • val = -1, colIndex = 2 → columns[2].push(-1) → columns는 [[1, 4], [-1, 5], [3, -1]]
  3. 세 번째 행 [-1, 8, 9]에 대해:
    • val = -1, colIndex = 0 → columns[0].push(-1) → columns는 [[1, 4, -1], [-1, 5], [3, -1]]
    • val = 8, colIndex = 1 → columns[1].push(8) → columns는 [[1, 4, -1], [-1, 5, 8], [3, -1]]
    • val = 9, colIndex = 2 → columns[2].push(9) → columns는 [[1, 4, -1], [-1, 5, 8], [3, -1, 9]]

이 과정을 통해 columns 배열은 matrix의 각 열을 분리하여 저장

 

 

 

 

Math.max(...columns[colIndex])

  • 전개 연산자(spread operator) ...는 배열이나 객체의 요소를 개별적으로 펼치는 데 사용
const numbers = [1, 2, 3];
Math.max(numbers) // 결과: NaN



const numbers = [1, 2, 3];
Math.max(...numbers) // 결과: 3