[LeetCode] 1351. Count Negative Numbers in a Sorted Matrix

Chobby·2025년 8월 12일
1

LeetCode

목록 보기
504/582

😎풀이

  1. grid 순회
    1-1. 현재 요소가 양수라면 생략
    1-2. 현재 요소가 음수라면 현재 요소 이후 요소들은 모두 음수 이므로 합산 및 다음 행 탐색색
  2. 모든 음수의 수를 반환
function countNegatives(grid: number[][]): number {
    const rowMax = grid.length
    const colMax = grid[0].length
    let negatives = 0
    for(let row = 0; row < rowMax; row++) {
        for(let col = 0; col < colMax; col++) {
            if(grid[row][col] >= 0) continue
            negatives += colMax - col
            break
        }
    }
    return negatives
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글