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.

Have you met this question in a real interview?

Yes
Example

Given matrix

[
[1 ,5 ,7],
[3 ,7 ,-8],
[4 ,-8 ,9],
]

return [(1,1), (2,2)]

Challenge

O(n3) time.

这道题跟LeetCode上的那道Max Sum of Rectangle No Larger Than K很类似。

解法一:

class Solution {
public:
/**
* @param matrix an integer matrix
* @return the coordinate of the left-up and right-down number
*/
vector<vector<int>> submatrixSum(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[].empty()) return {};
vector<vector<int>> sums = matrix;
int m = matrix.size(), n = matrix[].size();
for (int i = ; i < m; ++i) {
for (int j = ; j < n; ++j) {
int t = sums[i][j];
if (i > ) t += sums[i - ][j];
if (j > ) t += sums[i][j - ];
if (i > && j > ) t -= sums[i - ][j - ];
sums[i][j] = t;
for (int p = ; p <= i; ++p) {
for (int q = ; q <= j; ++q) {
int d = sums[i][j];
if (p > ) d -= sums[p - ][j];
if (q > ) d -= sums[i][q - ];
if (p > && q > ) d += sums[p - ][q - ];
if (d == ) return {{p, q}, {i, j}};
}
}
}
}
printVec(sums);
return {};
}
};

解法二:

class Solution {
public:
/**
* @param matrix an integer matrix
* @return the coordinate of the left-up and right-down number
*/
vector<vector<int>> submatrixSum(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[].empty()) return {};
int m = matrix.size(), n = matrix[].size();
for (int i = ; i < n; ++i) {
vector<int> sums(m, );
for (int j = i; j < n; ++j) {
for (int k = ; k < m; ++k) {
sums[k] += matrix[k][j];
}
int curSum = ;
unordered_map<int, int> map{{,-}};
for (int k = ; k < m; ++k) {
curSum += sums[k];
if (map.count(curSum)) return {{map[curSum] + , i}, {k, j}};
map[curSum] = k;
}
}
}
return {};
}
};

参考资料:

http://www.jiuzhang.com/solutions/submatrix-sum/

最新文章

  1. 采用cocos2d-x lua 制作数字滚动效果样例
  2. bzoj3316: JC loves Mkk
  3. ubuntu 常用命令集合版(二)【大侠勿喷,菜鸟欢迎】(转)
  4. C# C/S WPF 远程操作服务器上面的文件
  5. HttpClient和HttpURLConnection整合汇总对比
  6. 实例--post请求,完成一个抽奖程序概率的测试
  7. Linux 内核模块设计
  8. Redux1
  9. apache 2.4.9 配置其他客户端访问 required all granted
  10. Apache+php+mysql win7 64位安装的几个注意事项
  11. XWalkView+html 开发Android应用
  12. C/C++取出变量的每一位的值(第一次知道还有QBitArray)
  13. luogu P4074 [WC2013]糖果公园
  14. ubuntu12.04安装Docker
  15. Android 播放内部mp3音乐
  16. vue使用日期时间插件layDate
  17. Guava HashMultiset(MultiSet)
  18. Linux ip命令详解
  19. 用 Delphi 7 实现基于 FFMS2 的视频转 GIF 工具 [原创]
  20. poj 1218 THE DRUNK JAILER

热门文章

  1. WebRTC之带宽控制部分学习(1) ------基本demo的介绍
  2. linux下vim配置以及一些常用的快捷键
  3. 硬件断点 DrxHook
  4. Ubuntu 14.04下翻译软件的安装与比较
  5. Web Tours自带示例网站无法打开的解决方案
  6. js Array对象
  7. mac下mysql的安装
  8. 20145223《Java程序设计》实验报告3
  9. 微軟将从 .NET 4 以后的版本弃用 System.Data.OracleClient 以及Oracle 的各种连接方法
  10. 数据库的SQL语句创建和主外键删除操作