九章算法高级班笔记7.Follow Up Question

Overview: cs3k.com 

  1. Subarray sum 3 follow up
  2. Continuous Subarray Sum 2 follow up
  3. Wiggle Sort 2 follow up
  4. Partition 3 follow up
  5. 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

转载于:https://www.cnblogs.com/jiuzhangsuanfa/p/9895699.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值