알고리즘/해결

LeetCode1351. Count Negative Numbers in a Sorted Matrix

언클린 2020. 2. 16. 14:37
728x90

1. 문제(원본)

Given a m * n matrix grid which is sorted in non-increasing order both row-wise and column-wise. 

Return the number of negative numbers in grid.

 

Example 1:

Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] Output: 8 Explanation: There are 8 negatives number in the matrix.

Example 2:

Input: grid = [[3,2],[1,0]] Output: 0

Example 3:

Input: grid = [[1,-1],[-1,-1]] Output: 3

Example 4:

Input: grid = [[-1]] Output: 1

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 100
  • -100 <= grid[i][j] <= 100

2. 문제

임의의 2차원 배열을 받아 음수의 수를 카운팅하라

3. 나의 답

class Solution {

    func countNegatives(_ grid: [[Int]]) -> Int {

        var count: Int = 0

        grid.forEach { (y) in

            y.forEach{ (x) in

                if x < 0 {

                    count += 1

                }

            }

        }

        return count

    }

}

4. 다른 유저의 답

없었다...

5. 마무리

이중for문으로 간단하게 풀 수 있는 문제였다. 

전 항목 확인이 필요하기 때문에 for in보다는 forEach가 나을 것 같아 forEach를 사용했다.

 

728x90