九章演算法高階班筆記7.Follow Up Question
阿新 • • 發佈:2018-11-02
Overview: cs3k.com
- Subarray sum 3 follow up
- Continuous Subarray Sum 2 follow up
- Wiggle Sort 2 follow up
- Partition 3 follow up
- Iterator 3 follow up
Subarray Sum
cs3k.com
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; } }
Submatrix Sum
cs3k.com
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]