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를 사용했다.
'알고리즘 > 해결' 카테고리의 다른 글
LeetCode1221. Split a String in Balanced Strings (0) | 2020.02.23 |
---|---|
LeetCode771. Jewels and Stones (0) | 2020.02.23 |
LeetCode1342. Number of Steps to Reduce a Number to Zero (0) | 2020.02.16 |
LeetCode1295. Find Numbers with Even Number of Digits (0) | 2020.02.02 |
LeetCode1313. Decompress Run-Length Encoded List (0) | 2020.02.02 |