1351. Count Negative Numbers in a Sorted Matrix
class Solution {
public:
int binarySearch(vector<int>& arr){
int left = 0;
int right = arr.size() - 1;
int mid;
while(left <= right){
mid = left + (right - left) / 2;
if(arr[mid] >= 0){
left = mid + 1;
} else {
right = mid - 1;
}
}
return arr.size() - left;
}
int countNegatives(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
int ans = 0;
for(auto& arr: grid){
ans += binarySearch(arr);
}
return ans;
}
};
class Solution {
public:
int countNegatives(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
int ans = 0;
int index = n - 1;
for(auto& row : grid){
while(index >= 0 && row[index] < 0){
index--;
}
ans += (n - index - 1);
}
return ans;
}
};