原题链接在这里:http://www.lintcode.com/zh-cn/problem/sliding-window-matrix-maximum/
题目:
Given an array of n * m
matrix, and a moving matrix window (size k * k
), move the window from top left to botton right at each iteration, find the maximum number inside the window at each moving.
Return 0
if the answer does not exist.
For matrix
[
[1, 5, 3],
[3, 2, 1],
[4, 1, 9],
]
The moving window size k = 2
.
return 13.
At first the window is at the start of the array like this
[
[|1, 5|, 3],
[|3, 2|, 1],
[4, 1, 9],
]
,get the sum 11
;
then the window move one step forward.
[
[1, |5, 3|],
[3, |2, 1|],
[4, 1, 9],
]
,get the sum 11
;
then the window move one step forward again.
[
[1, 5, 3],
[|3, 2|, 1],
[|4, 1|, 9],
]
,get the sum 10
;
then the window move one step forward again.
[
[1, 5, 3],
[3, |2, 1|],
[4, |1, 9|],
]
,get the sum 13
;
SO finally, get the maximum from all the sum which is 13
.
题解:
用sum matrix来表示以[i,j]为右下角点时整个左上方的matrix的和. sum[i][j] = matrix[i-1][j-1] + sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1].
需要减掉sum[i-1][j-1]因为加重复了.
然后每次算以[i][j]为右下角, 边长为k的小matrix的和, sum[i][j] - sum[i-k][j] - sum[i][j-k] + sum[i-k][j-k].
需要加上sum[i-k][j-k]因为减重复了.
Time Complexity: O(m*n), m = matrix.length, n = matrix[0].length.
Space: O(m*n).
AC Java:
1 public class Solution { 2 public int maxSlidingMatrix(int[][] matrix, int k) { 3 if(matrix == null || matrix.length < k || matrix[0].length < k){ 4 return 0; 5 } 6 int m = matrix.length; 7 int n = matrix[0].length; 8 int [][] sum = new int[m+1][n+1]; 9 for(int i = 1; i<=m; i++){ 10 for(int j = 1; j<=n; j++){ 11 sum[i][j] = matrix[i-1][j-1] + sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1]; 12 } 13 } 14 15 int res = Integer.MIN_VALUE; 16 for(int i = k; i<=m; i++){ 17 for(int j = k; j<=n; j++){ 18 res = Math.max(res, sum[i][j]-sum[i-k][j]-sum[i][j-k]+sum[i-k][j-k]); 19 } 20 } 21 return res; 22 } 23 }