관리 메뉴

솜씨좋은장씨

[leetCode] 1351. Count Negative Numbers in a Sorted Matrix (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 1351. Count Negative Numbers in a Sorted Matrix (Python)

솜씨좋은장씨 2020. 11. 3. 00:11
728x90
반응형

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

Solution

class Solution:
    def countNegatives(self, grid: List[List[int]]) -> int:
        answer = 0
        
        for i in range(len(grid)):
            if grid[i][-1] < 0:
                for j in range(len(grid[i])-1, -1, -1):
                    if grid[i][j] >= 0:
                        break
                    else:
                        answer = answer + 1
            else:
                continue
        return answer

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments