Given an integer array, find a subarray where the sum of numbers is zero. Your code should return the index of the first number and the index of the last number.
Notice
There is at least one subarray that it’s sum equals to zero.
Have you met this question in a real interview? Yes
Example
Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].
public class Solution {
/**
* @param nums: A list of integers
* @return: A list of integers includes the index of the first number
* and the index of the last number
*/
public ArrayList<Integer> subarraySum(int[] nums) {
// write your code here
int len = nums.length;
ArrayList<Integer> ans = new ArrayList<Integer>();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(0, -1);
int sum = 0;
for (int i = 0; i < len; i++) {
sum += nums[i];
if (map.containsKey(sum)) {
ans.add(map.get(sum) + 1);
ans.add(i);
return ans;
}
map.put(sum, i);
}
return ans;
}
}
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)]
可以for循环暴力做
for lx = 0 ~ n
for ly = 0 ~ n
for rx = lx ~ n
for ry = ly ~ n
时间复杂度是O(n^4)
接着我们可以想枚举行, 对于
[1 , 5 , 7]
[3 , 7 ,-8]
[4 ,-8 , 9]
的第0行和第1行来说,我们算出每列的sum:
[1 , 5 , 7]
[3 , 7 , -8]
sum [4 , 12, -1]
然后我们就把每个列变成了一个列的和的值;
所以寻找二维的子矩阵就变成了寻找一维的子数组问题。
public class Solution {
/**
* @param matrix an integer matrix
* @return the coordinate of the left-up and right-down number
*/
public int[][] submatrixSum(int[][] matrix) {
int[][] result = new int[2][2];
int M = matrix.length;
if (M == 0) return result;
int N = matrix[0].length;
if (N == 0) return result;
// pre-compute: sum[i][j] = sum of submatrix [(0, 0), (i, j)]
int[][] sum = new int[M+1][N+1];
for (int j=0; j<=N; ++j) sum[0][j] = 0;
for (int i=1; i<=M; ++i) sum[i][0] = 0;
for (int i=0; i<M; ++i) {
for (int j=0; j<N; ++j)
sum[i+1][j+1] = matrix[i][j] + sum[i+1][j] + sum[i][j+1] - sum[i][j];
}
for (int l=0; l<M; ++l) {
for (int h=l+1; h<=M; ++h) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int j=0; j<=N; ++j) {
int diff = sum[h][j] - sum[l][j];
if (map.containsKey(diff)) {
int k = map.get(diff);
result[0][0]