zoukankan      html  css  js  c++  java
  • 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.

    Subarray Sum的follow up。求二维矩阵上和为0的submatrix. 

    这题暴力解法枚举左上两坐标,右下两坐标,求中间和。复杂度为O(n^6)。太高。

    比较好的办法是枚举子矩阵的开始行和结束行,之后以subarray sum的思路,用hashmap发现左边界和右边界。

    为了高效求的开始行和结束行之间每一列的sum,可以先求得以(0,0)开始,右下坐标结束的submatrix sum。复杂度为O(m,n)。这一点比较神奇。

    总体复杂度为O(n^2*m).代码如下:

    class Solution:
        # @param {int[][]} matrix an integer matrix
        # @return {int[][]} the coordinate of the left-up and right-down number
        def submatrixSum(self, matrix):
            """
            1.enumerate the down-right corner, compute the sum firstly
            2.enumerate the begin line and end line, find the submatrix just like the subarry(traverse the right line) 
            """
            res = [[0,0],[0,0]]
            if not matrix or not matrix[0]:
                return res
            m = len(matrix)
            n = len(matrix[0])
            
            presum = [[0] * (n+1) for i in xrange(m+1)]
            for i in xrange(m):  #求以(0,0)开始,右下坐标结束的子矩阵的复杂度。
                for j in xrange(n):
                    presum[i+1][j+1] = presum[i][j+1] + presum[i+1][j] - presum[i][j] + matrix[i][j]
            for l in xrange(m):
                for h in xrange(l+1,m+1):
                    hash = {}
                    for r in xrange(0, n+1):
                        diff = presum[h][r] - presum[l][r]
                        if diff not in hash:
                            hash[diff] = r
                        else:
                            res[0][0] = l
                            res[0][1] = hash[diff]
                            res[1][0] = h - 1
                            res[1][1] = r-1
                            
            return res
  • 相关阅读:
    运营设计方法论
    使用 typescript ,提升 vue 项目的开发体验(2)
    PAT 1078. 字符串压缩与解压
    PAT 1077. 互评成绩计算
    PAT 1076. Wifi密码
    PAT 1075. 链表元素分类
    PAT 1074. 宇宙无敌加法器
    PAT 1073. 多选题常见计分法
    PAT 1072. 开学寄语
    PAT 1071. 小赌怡情
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5697516.html
Copyright © 2011-2022 走看看