Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit d18c7fb

Browse files
committedFeb 16, 2020
Count Negative Numbers in a Sorted Matrix
1 parent b4ccce1 commit d18c7fb

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
 
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/
3+
4+
Given a m * n matrix grid which is sorted in non-increasing order both row-wise and column-wise.
5+
6+
Return the number of negative numbers in grid.
7+
8+
Example 1:
9+
Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
10+
Output: 8
11+
Explanation: There are 8 negatives number in the matrix.
12+
13+
Example 2:
14+
Input: grid = [[3,2],[1,0]]
15+
Output: 0
16+
17+
Example 3:
18+
Input: grid = [[1,-1],[-1,-1]]
19+
Output: 3
20+
21+
Example 4:
22+
Input: grid = [[-1]]
23+
Output: 1
24+
25+
Constraints:
26+
m == grid.length
27+
n == grid[i].length
28+
1 <= m, n <= 100
29+
-100 <= grid[i][j] <= 100
30+
"""
31+
# Time Complexity: O(m+n)
32+
# Space Complexity: O(1)
33+
class Solution:
34+
def countNegatives(self, grid: List[List[int]]) -> int:
35+
m, n = len(grid), len(grid[0])
36+
row, column, count = m-1, 0, 0
37+
while row >= 0 and column < n:
38+
if grid[row][column] < 0:
39+
count += (n-column)
40+
row -= 1
41+
else:
42+
column += 1
43+
return count
44+
45+
46+
# Time Complexity: O(m*n)
47+
# Space Complexity: O(1)
48+
class Solution1:
49+
def countNegatives(self, grid: List[List[int]]) -> int:
50+
count = 0
51+
for i in range(len(grid)):
52+
for j in range(len(grid[0])):
53+
if grid[i][j] < 0:
54+
count += 1
55+
return count

0 commit comments

Comments
 (0)
Please sign in to comment.