LintCode Sliding Window Matrix Maximum

原题链接在这里: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 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/6382402.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值