problems(cpp): add “1351. Count Negative Numbers in a Sorted Matrix”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-06-08 16:27:36 +02:00
parent c74dc48221
commit 6e2c2c2fbd
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,30 @@
#include <algorithm>
#include <cassert>
#include <vector>
class Solution {
public:
int countNegatives(const std::vector<std::vector<int>>& grid)
{
auto last = 0;
auto negatives = 0;
for (const auto& row : grid) {
auto first_positive = std::lower_bound(row.crbegin() + last, row.crend(), 0);
auto i = first_positive - row.crbegin();
negatives += i;
last = i;
}
return negatives;
}
};
int main()
{
Solution s;
assert((s.countNegatives(std::vector { std::vector { 4, 3, 2, -1 }, std::vector { 3, 2, 1, -1 }, std::vector { 1, 1, -1, -2 }, std::vector { -1, -1, -2, -3 } }) == 8));
assert((s.countNegatives(std::vector { std::vector { 3, 2 }, std::vector { 1, 0 } }) == 0));
return 0;
}