problems(cpp): add “1351. Count Negative Numbers in a Sorted Matrix”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
c74dc48221
commit
6e2c2c2fbd
1 changed files with 30 additions and 0 deletions
30
problems/cpp/count-negative-numbers-in-a-sorted-matrix.cpp
Normal file
30
problems/cpp/count-negative-numbers-in-a-sorted-matrix.cpp
Normal 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;
|
||||
}
|
Loading…
Reference in a new issue