[LeetCode] Range Sum Query 2D - Immutable

來源:互聯網
上載者:User

標籤:

Very similar to Range Sum Query - Immutable, but we now need to compute a 2d accunulated-sum. In fact, if you work in computer vision, you may know a name for such an array --- Integral Image.

To solve this problem, Stefan has already posted a very elegant solution.

The code is copied here.

 1 class NumMatrix { 2 public: 3     NumMatrix(vector<vector<int>> &matrix) { 4         accu = matrix; 5         for (int i = 0; i < matrix.size(); i++) 6             for (int j = 0; j < matrix[0].size(); j++) 7                 accu[i][j] += a(i-1, j) + a(i, j-1) - a(i-1, j-1); 8     } 9 10     int sumRegion(int row1, int col1, int row2, int col2) {11         return a(row2, col2) - a(row1-1, col2) - a(row2, col1-1) + a(row1-1, col1-1);12     }13 private:14     vector<vector<int>> accu;15     int a(int i, int j) {16         return i >= 0 && j >= 0 ? accu[i][j] : 0;17     }18 };19 20 21 // Your NumMatrix object will be instantiated and called as such:22 // NumMatrix numMatrix(matrix);23 // numMatrix.sumRegion(0, 1, 2, 3);24 // numMatrix.sumRegion(1, 2, 3, 4);

 

[LeetCode] 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.