Below is the top 7 difference between C++ Reference vs Pointer
Q
Given a
m * 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
Example 3:
Input: grid = [[1,-1],[-1,-1]] Output: 3
Example 4:
Input: grid = [[-1]] Output: 1
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100
A:
class Solution {
public:
int countNegatives(vector<vector<int>>& grid) {
if ( grid.size()==0 || grid[0].size() == 0)
return 0;
return helper(grid,0,0,grid.size(),grid[0].size());
}
private:
int helper(vector<vector<int>>& grid, int X1, int Y1, const int m, const int n) {
if (X1>=m || Y1>=n )
{
return 0;
}
if (grid[X1][Y1]< 0)
{
return (m-X1) * (n-Y1);
}
int res = 0;
// linear search a row
vector<int> & row = grid[X1];
for (int j = Y1+1; j<n; ++j )
{
if(row[j]<0)
{
res += n-j;
break;
}
}
// linear search a column
for (int i = X1+1; i<m; ++i)
{
if(grid[i][Y1]<0)
{
res += m -i;
break;
}
}
#
res +=helper(grid, X1+1, Y1+1, m, n);
return res;
}
};
Do this hack to drop 2 lbs of fat in 8 hours
ReplyDeleteMore than 160 000 men and women are utilizing a easy and SECRET "liquids hack" to lose 1-2 lbs every night as they sleep.
It is proven and it works all the time.
This is how to do it yourself:
1) Get a clear glass and fill it up with water half full
2) Now do this amazing hack
so you'll become 1-2 lbs skinnier as soon as tomorrow!