国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LeetCode] 304. Range Sum Query 2D - Immutable

chinafgj / 2108人閱讀

Problem

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

https://leetcode.com/static/i...

The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

Example:

Given matrix = [
  [3, 0, 1, 4, 2],
  [5, 6, 3, 2, 1],
  [1, 2, 0, 1, 5],
  [4, 1, 0, 1, 7],
  [1, 0, 3, 0, 5]
]

sumRegion(2, 1, 4, 3) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12

Note:
You may assume that the matrix does not change.
There are many calls to sumRegion function.
You may assume that row1 ≤ row2 and col1 ≤ col2.

Solution
class NumMatrix {
    int[][] sum;
    public NumMatrix(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return;
        }
        int m = matrix.length, n = matrix[0].length;
        this.sum = new int[m+1][n+1];

        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                sum[i][j] = sum[i-1][j]+sum[i][j-1]-sum[i-1][j-1]+matrix[i-1][j-1];
            }
        }
    }
    
    public int sumRegion(int row1, int col1, int row2, int col2) {
        return sum[row2+1][col2+1]-sum[row2+1][col1]-sum[row1][col2+1]+sum[row1][col1];
    }
}

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/72230.html

相關文章

  • leetcode303-304 Range Sum Query Immutable

    摘要:假設有一個整數數組,計算下標從到包含和的數字的和。求和的請求將會在同一個整數數組上多次請求。這一題思路很簡單,因為。而利用動態規劃則很容易知道。這里將原先的一維數組替換成二維數組。要求計算一個矩形內的所有元素的值。 Range Sum Query Immutable Given an integer array nums, find the sum of the elements be...

    Worktile 評論0 收藏0
  • [LeetCode] Range Sum Query Immutable

    Problem Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRan...

    LiuZh 評論0 收藏0
  • Range Sum Query

    摘要:表現在二進制上的規律每次加上最末尾的求末尾的就拿這個數和它的補碼于。還有要求不是,要轉換一下,和之前那道的思路差不多。這里用一個的表示從到的和。 Range Sum Query - Immutable Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), i...

    zhongmeizhi 評論0 收藏0
  • leetcode307. Range Sum Query - Mutable

    摘要:題目要求可以先參考數組不發生變動時的題目。最后的葉節點為當前數組的值,非葉結點則記錄了子數組的范圍以及該子數組中所有元素的和。它是一個非常輕量級的數據結構,而且幾乎就是為這種題目量身打造。 題目要求 Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inc...

    Lemon_95 評論0 收藏0
  • LeetCode 攻略 - 2019 年 7 月下半月匯總(100 題攻略)

    摘要:月下半旬攻略道題,目前已攻略題。目前簡單難度攻略已經到題,所以后面會調整自己,在刷算法與數據結構的同時,攻略中等難度的題目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道題,目前已攻略 100 題。 一 目錄 不折騰的前端,和咸魚有什么區別...

    tain335 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<