aboutsummaryrefslogtreecommitdiff
path: root/other/count_negative_num_matrix.cpp
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
committerJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
commit7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch)
treeeb7a24ee2067f92245c57bb118e85a1baf15df50 /other/count_negative_num_matrix.cpp
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directory
Diffstat (limited to 'other/count_negative_num_matrix.cpp')
-rw-r--r--other/count_negative_num_matrix.cpp37
1 files changed, 37 insertions, 0 deletions
diff --git a/other/count_negative_num_matrix.cpp b/other/count_negative_num_matrix.cpp
new file mode 100644
index 0000000..f7c776d
--- /dev/null
+++ b/other/count_negative_num_matrix.cpp
@@ -0,0 +1,37 @@
+// 1351. Count Negative Numbers in a Sorted Matrix
+#include "leetcode.h"
+
+// given an 'm x n' matrix 'grid' which is sorted in non-increasing order both
+// row-wise and column-wise, return the number of negative numbers in 'grid'
+
+class Solution {
+public:
+ int countNegatives(vvd & grid) {
+ int ans = 0;
+ for (vector<int> row : grid)
+ for (int i : row)
+ if (i < 0)
+ ans++;
+ return ans;
+ for (vector<int> row : grid)
+ ans += upper_bound(row.rbegin(), row.rend(), -1) - row.rbegin();
+ return ans;
+ int m = grid.size(), n = grid[0].size(), r = 0, c = n - 1;
+ while (r < m) {
+ while (c >= 0 && grid[r][c] < 0)
+ c--;
+ ans += n - c - 1;
+ r++;
+ }
+ return ans;
+ }
+};
+
+int main() {
+ Solution obj;
+ vvd
+ g1 = {{4, 3, 2, -1}, {3, 2, 1, -1}, {1, 1, -1, -2}, {-1, -1, -2, -3}};
+ vvd g2 = {{3, 2}, {1, 0}};
+ printf("%d\n", obj.countNegatives(g1)); // expect: 8
+ printf("%d\n", obj.countNegatives(g2)); // expect: 0
+}