Lintcode 405. Submatrix Sum

题目

Given an integer matrix, find a submatrix where the sum of numbers is zero. Your code should return the coordinate of the left-up and right-down number.

Example Given matrix

[ [1 ,5 ,7], [3 ,7 ,-8], [4 ,-8 ,9], ] return [(1,1), (2,2)]

思路

这道题是从subarray sum equals定值k 转化成submatrix sum equals 定值k,我们要使用一个column prefix sum把整个matrix转化回一个array求解。唯一不一样的地方是我们这时需要额外两个for loop去枚举submatrix的上下端点。但是在innermost for loop,思路和array是完全一样的。

复杂度

time O(n^3), space O(n)

代码

  public class Solution {
    /**
     * @param matrix an integer matrix
     * @return the coordinate of the left-up and right-down number
     */
    public int[][] submatrixSum(int[][] matrix) {
        // Write your code here
        // check edge case
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return new int[0][0];
        }
        // preprocess
        int row = matrix.length;
        int col = matrix[0].length;

        for (int i = 1; i < row; i++) {
            for (int j = 0; j < col; j++) {
                matrix[i][j] += matrix[i - 1][j];
            }
        }
        // main
        for (int i = 0; i < row; i++) {
            for (int k = i; k < row; k++) {
                HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
                map.put(0, -1);
                int prefix = 0;
                for (int j = 0; j < col; j++) {
                    int longCol = matrix[k][j];
                    int shortCol = i == 0? 0 : matrix[i-1][j];
                    prefix += longCol - shortCol;

                    if (map.containsKey(prefix)) {
                        int leftUpRow = i;
                        int leftUpCol = map.get(prefix);
                        int rightDownRow = k;
                        int rightDownCol = j;
                        return new int[][]{{leftUpRow, leftUpCol + 1}, {rightDownRow, rightDownCol}};
                    } else {
                        map.put(prefix, j);
                    }
                }
            }
        }
        return new int[0][0];
    }
}

results matching ""

    No results matching ""