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.java
Noticenode
There is at least one subarray that it’s sum equals to zero.c++
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.app
Example
Given matrixdom
[1 , 5 , 7] [3 , 7 ,-8] [4 ,-8 , 9]
return [(1,1), (2,2)]ide
能夠for循環暴力作函數
for lx = 0 ~ n for ly = 0 ~ n for rx = lx ~ n for ry = ly ~ n
時間複雜度是O(n^4)優化
接着咱們能夠想枚舉行, 對於ui
[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] = l