[LeetCode] 304. Range Sum Query 2D - Immutable

Chobby·2025년 3월 7일
1

LeetCode

목록 보기
278/427

😎풀이

  1. this.matrix로 생성 인자를 할당한다.
  2. row1 <= row2, col1 <= col2가 보장되어 있으므로 사잇값을 순회하며 모든 인자를 더한다.
  3. 더한 결과를 반환한다.
class NumMatrix {
    private matrix: number[][]
    constructor(matrix: number[][]) {
        this.matrix = matrix
    }

    sumRegion(row1: number, col1: number, row2: number, col2: number): number {
        let sum = 0
        for(let row = row1; row <= row2; row++) {
            for(let col = col1; col <= col2; col++) {
                sum += this.matrix[row][col]
            }
        }
        return sum
    }
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글