This is an easy problem with the description being:
You are given an n x n integer matrix grid.
Generate an integer matrix maxLocal of size (n - 2) x (n - 2) such that:
maxLocal[i][j] is equal to the largest value of the 3 x 3 matrix in grid centered around row i + 1 and column j + 1.
In other words, we want to find the largest value in every contiguous 3 x 3 matrix in grid.
Return the generated matrix.
As the problem states, the result needs to be a smaller matrix where each item should be the largest among it’s neighbors. With that in mind, there isn’t much to do besides following the conditions, which is traverse the grid, on each variable check it’s neighbors and get the largest.
The result would be:
class Solution {
public int[][] largestLocal(int[][] grid) {
final int [][] response = new int[grid.length - 2][grid[0].length - 2];
for(int i=1 ; i < (grid.length-1) ; i++) {
for(int j=1; j < (grid[i].length-1) ; j++) {
response[i-1][j-1] = findLargestAmontNeighbors(grid, i, j);
}
}
return response;
}
public int findLargestAmontNeighbors(final int[][] grid, final int i, final int j) {
int largest = 0;
for(int a=-1 ; a < 2 ; a++) {
for(int b=-1 ; b < 2 ; b++) {
if (largest < grid[i+a][j+b]) {
largest = grid[i+a][j+b];
}
}
}
return largest;
}
Runtime: 3ms, faster than 66.48% of Java online submissions.
Memory Usage: 45.72 MB, less than 38.80% of Java online submissions.
A simple improvement here that can be done would be when defining a and b use the indexes already instead of calculate later, but that’s a very small one.
—
That’s it! If there is anything thing else to discuss feel free to drop a comment, if I missed anything let me know so I can update accordingly.
Until next post! :)
Top comments (0)