Submatrix Sum
Last updated
Was this helpful?
Last updated
Was this helpful?
LintCode 405
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
return
[(1,1), (2,2)]
O(n^3) time.
求 submatrix sum,可以用 Range Sum Query 2D - Immutable 的方法,就是先求个类似prefixsum[i][j]数组。
然后对 row1, col2, row2, col2 来做4重循环,求 sum 为0的 submatrix。这样的话时间复杂度是 O(N^4),而题目要求O(N^3)。看了下九章的答案,做的比较巧妙,对 row1, row2 循环,然后对 col 循环,一边循环一边把 sum 放在 hash map 的。然后对照。具体需要看code
另外一个做法可以叫做 2d Kadane's Algorithm.
思想一样的,就是把数组拉片,然后把片压成一维数组。下面是截图:
压缩这个过程貌似是 O(N^2) 的感觉,但是,具体流程里面,右边这个一维数组是逐步更新的,所以 amortized cost 是 O(N)
按照这个思路,写下程序
两个程序的时间复杂度都是O(N^3)。九章那个方法借用了一个2维数组,所以空间复杂度较大。不过解释起来稍微容易点。
一道类似的题,Maximum Sub Subrectangle, 这里有视频教程
用 L, R 两个指针把数组拉片,然后压缩成右边那个一维数组,然后在这个数组里面操作。
这个网页也讲这题: