Problem: Given a 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.
Example:
Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] Output: 8 Explanation: There are 8 negatives number in the matrix.
Input: grid = [[3,2],[1,0]] Output: 0
Approach: Given we have a matrix which is sorted row wise and column wise, we can use the approach which we have used in the problem of searching an element in row wise and column wise sorted matrix.
Here, I am going to start from bottom left corner as the matrix is sorted in descending order but we can solve this problem starting from top right corner too.
Implementation in C#:
public int CountNegatives(int[][] grid)
{
int rows = grid?.Length ?? 0;
if (rows == 0)
{
return 0;
}
int cols = grid[0].Length;
int row = rows - 1, col = 0;
int totalNegNums = 0;
while (row >= 0 && col < cols)
{
if (grid[row][col] < 0)
{
totalNegNums += (cols - col);
--row;
}
else
{
++col;
}
}
return totalNegNums;
}
Complexity: O(m + n)
No comments:
Post a Comment