• [LintCode] 1840. Matrix restoration


    There is a matrix beforebefore with nn rows and mm columns. For each element in before before[i][j]before[i][j], we will use the following algorithm to convert it to after [i] [j]after[i][j]. Given the afterafter matrix, please restore the original matrix beforebefore.

    s = 0
    for i1: 0 -> i
        for j1: 0 -> j
            s = s + before[i1][j1]
    after[i][j] = s
    

    Example

    Input:
    2
    2
    [[1,3],[4,10]]
    Output: [[1,2],[3,4]]
    Explanation:
    before:
    1 2
    3 4
    
    after:
    1 3
    4 10


    public class Solution {
        /**
         * @param n: the row of the matrix
         * @param m: the column of the matrix
         * @param after: the matrix
         * @return: restore the matrix
         */
        public int[][] matrixRestoration(int n, int m, int[][] after) {
            // write your code here
            // pre[i][j] = pre[i - 1][j] + pre[i][j - 1] - pre[i- 1][j - 1] + grid[i][j]
            // grid[i][j] = pre[i][j] - pre[i - 1][j] - pre[i][j - 1] + pre[i- 1][j - 1] 
            int[][] res = new int[after.length][after[0].length];
            for(int i = 0; i < after.length; i++) {
                for (int j = 0; j < after[0].length; j++) {
                    res[i][j] = after[i][j];
                    if (i > 0) {
                        res[i][j] -= after[i - 1][j];
                    }
                    if (j > 0) {
                        res[i][j] -= after[i][j - 1];
                    }
                    if (i > 0 && j > 0) {
                        res[i][j] += after[i - 1][j - 1];
                    }
                }
            }
            return res;
        }
    }
  • 相关阅读:
    累加和最大化
    SELECT子句顺序
    Linux命令入门教程
    求字符串前缀最长的连续重复子串(不重叠)
    王道机试指南题解(C/C++版)
    C++ Primer 第 5 版 习题参考答案
    第 16 章
    第 15 章
    第 14 章
    从jvm源码解读Java运行时的类加载
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12515474.html
Copyright © 2020-2023  润新知