1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00
LeetCode/problems/cpp/count-negative-numbers-in-a-sorted-matrix.cpp

31 lines
803 B
C++
Raw Normal View History

#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;
}