Range Sum Query 2D - Immutable

來源:互聯網
上載者:User

標籤:產生   code   const   方便   problem   調用   query   比較   div   

https://leetcode.com/problems/range-sum-query-2d-immutable/

 

條件說sumRegion 會調很多次,如果每次都用雙for 迴圈去累加的話就有太多重複計算了,所以可以實現cache 一下。

可以有兩種cache 機制,一種是在初始化的時候就產生cache 這樣初始化時間比較長應該是O(n*m) 但是sumRegion 方法就方便和高效多了,大概是O(1)

另一種是動態更新cache,隨著sumRegion 的調用慢慢建立cache,這樣處理起來會比較麻煩,但是初始化時間就可以忽略不計了,在sumRegion 的多次調用中慢慢的速度越來越快。

 

我才用第一種方式,初始化時候建立cache,cache 同樣是n*m 的矩陣,每個元素是當前行的累加和。

調用sumRegion 的時候把每行的指定列範圍內的和加起來就行了,而每行的和就用兩個邊際列的cache 值只差加上左邊際列的原始值就行了,即:

rowSum = cache[endCol] - cache[starCol] + origin[starCol]

 

/** * @constructor * @param {number[][]} matrix */var NumMatrix = function(matrix) {    if (matrix.length === 0) return;    this.cache = [];    this.matrix = matrix;    this.row = matrix.length;    this.col = matrix[0].length;    for (var i = 0; i < this.row; i++) {        var acc = 0;        this.cache.push([]);        for (var j = 0; j < this.col; j++) {            acc += matrix[i][j];            this.cache[i].push(acc);        }    }    // console.log(this.cache);};/** * @param {number} row1 * @param {number} col1 * @param {number} row2 * @param {number} col2 * @return {number} */NumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) {    var sum = 0;    if (!this.matrix) return 0;    for (var i = row1; i <= row2; i++) {        sum += this.cache[i][col2] - this.cache[i][col1] + this.matrix[i][col1];    }    return sum;};

 

Range Sum Query 2D - Immutable

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.