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
  • 相关阅读:
    clientX和clientY属性需要注意的地方
    事件冒泡 --- 仿select下拉框
    body和document的梗
    完美运动框架
    仿flash运动框架
    多物体运动框架
    Computed Styles
    悬浮框
    【一起驴友】公司笔试
    Client Dimensions , offsetHeight , scrollTop 属性详解
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5697516.html
Copyright © 2011-2022 走看看