Home Count Negative Numbers in a Sorted Matrix
Post
Cancel

Count Negative Numbers in a Sorted Matrix

Leetcode Problem

Count Negative Numbers in a Sorted Matrix

이중 for문에서 음수의 개수를 구하는 문제입니다.

1
2
3
class Solution:
    def countNegatives(self, grid: List[List[int]]) -> int:
        return len([ y for x in grid for y in x if y < 0 ])

음수들을 배열에 저장하기 때문에 성능은 안 좋지만 보기 좋게 한 줄로 풀어봤습니다.
이중 for문을 한 줄로 표현하는 방법을 쉽게 기억하기 위해서는 처음 y 뒤를 끊고 두 번째 for 앞을 끊어서 생각하면, grid에서 x를 뽑아내고 x에서 y를 뽑아낸다고 생각할 수 있습니다.





참고

This post is licensed under CC BY 4.0 by the author.