Count Negative Number in Matrix
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 1:
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.
Example 2:
Input: grid = [[3,2],[1,0]]
Output: 0
Brute Force:
class Solution {
public int countNegatives(int[][] grid) {
int row=grid.length;
int col=grid[0].length;
int negativeCount=0;
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
if(grid[i][j]<0)
{
negativeCount++;
}
}
}
return negativeCount;
}
}
Optimal Approach: Binary Search (O(m log n))
Since each row is sorted in decreasing order, we can apply binary search on each row to efficiently find the first negative number's index.
Algorithm:
-
Initialize
count = 0
. -
Iterate through each row in the matrix.
-
Apply binary search to find the first negative number in the row.
-
The number of negative numbers in the row is
total_columns - index_of_first_negative
. -
Accumulate this count for the final answer.
class Solution {
public int countNegatives(int[][] grid) {
// Get the number of rows and columns in the matrix
int row = grid.length;
int col = grid[0].length;
int negativeCount = 0; // Counter to store the total count of negative numbers
// Iterate through each row of the matrix
for (int i = 0; i < row; i++) {
int start = 0; // Left pointer for binary search
int end = col - 1; // Right pointer for binary search
// Perform binary search in the current row
while (start <= end) {
int mid = start + (end - start) / 2; // Calculate the middle index
if (grid[i][mid] < 0) {
// If the mid element is negative, move left (search for earlier negatives)
end = mid - 1;
} else {
// If mid is non-negative, move right to find first negative
start = mid + 1;
}
}
// After binary search, `start` points to the first negative element in the row
// All elements from `start` to `col - 1` are negative
negativeCount += (col - start);
}
return negativeCount; // Return the total count of negative numbers in the matrix
}
}
Comments
Post a Comment