-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1351. Count Negative Numbers in a Sorted Matrix
52 lines (40 loc) · 1.56 KB
/
1351. Count Negative Numbers in a Sorted Matrix
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*1351. Count Negative Numbers in a Sorted Matrix
Runtime: 1 ms, faster than 50.09% of Java online submissions for Count Negative Numbers in a Sorted Matrix.
Memory Usage: 39.4 MB, less than 63.38% of Java online submissions for Count Negative Numbers in a Sorted Matrix.*/
class Solution {
public int countNegatives(int[][] grid) {
int count=0;
for(int i=0;i<grid.length;i++)
for(int j=0;j<grid[0].length;j++)
if(grid[i][j]<0)
count++;
return count;
}
}
/* 1351. Count Negative Numbers in a Sorted Matrix
Runtime: 0 ms, faster than 100.00% of Java online submissions for Count Negative Numbers in a Sorted Matrix.
Memory Usage: 39.2 MB, less than 78.44% of Java online submissions for Count Negative Numbers in a Sorted Matrix.*/
class Solution {
public int countNegatives(int[][] grid) {
int rows = grid.length, cols = grid[0].length;
int res = 0, lastNeg = cols - 1;
for (int row = 0; row < rows; row++) {
if (grid[row][0] < 0) {
res+=cols;
continue;
}
if (grid[row][cols - 1] > 0)
continue;
int l = 0, r = lastNeg;
while (l <= r) {
int m = l + (r - l)/2;
if (grid[row][m] < 0) {
r = m - 1;
} else
l = m + 1;
}
res += (cols - l); lastNeg = l;
}
return res;
}
}