日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 308. 二维区域和检索 - 可变(前缀和)

發(fā)布時(shí)間:2024/7/5 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 308. 二维区域和检索 - 可变(前缀和) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

文章目錄

    • 1. 題目
    • 2. 解題

1. 題目

給你一個(gè) 2D 矩陣 matrix,請(qǐng)計(jì)算出從左上角 (row1, col1) 到右下角 (row2, col2) 組成的矩形中所有元素的和。

上述粉色矩形框內(nèi)的,該矩形由左上角 (row1, col1) = (2, 1) 和右下角 (row2, col2) = (4, 3) 確定。其中,所包括的元素總和 sum = 8。

示例: 給定 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 update(3, 2, 2) sumRegion(2, 1, 4, 3) -> 10注意: 矩陣 matrix 的值只能通過(guò) update 函數(shù)來(lái)進(jìn)行修改 你可以默認(rèn) update 函數(shù)和 sumRegion 函數(shù)的調(diào)用次數(shù)是均勻分布的 你可以默認(rèn) row1 ≤ row2,col1 ≤ col2

來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/range-sum-query-2d-mutable
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。

2. 解題

  • 類(lèi)似題目:LeetCode 304. 二維區(qū)域和檢索 - 矩陣不可變(DP)
  • 二維樹(shù)狀數(shù)組可以更高效,樹(shù)狀數(shù)組默寫(xiě)不來(lái)
  • 用行的前綴和做,時(shí)間復(fù)雜度O(n)
class NumMatrix {vector<vector<int>> mat;vector<vector<int>> rowpresum; public:NumMatrix(vector<vector<int>>& matrix) {mat = matrix;rowpresum = matrix;for(int i = 0, j; i < matrix.size(); ++i){for(j = 1; j < matrix[0].size(); ++j)rowpresum[i][j] = rowpresum[i][j-1] + matrix[i][j];}}void update(int row, int col, int val) {mat[row][col] = val;rowpresum[row][col] = (col > 0 ? rowpresum[row][col-1] : 0) + val;for(int j = col+1; j < mat[0].size(); ++j)rowpresum[row][j] = rowpresum[row][j-1] + mat[row][j];}int sumRegion(int row1, int col1, int row2, int col2) {int sum = 0;for(int i = row1; i <= row2; ++i){sum += rowpresum[i][col2] - (col1==0 ? 0 : rowpresum[i][col1-1]);}return sum;} };

28 ms 12.2 MB


我的CSDN博客地址 https://michael.blog.csdn.net/

長(zhǎng)按或掃碼關(guān)注我的公眾號(hào)(Michael阿明),一起加油、一起學(xué)習(xí)進(jìn)步!

總結(jié)

以上是生活随笔為你收集整理的LeetCode 308. 二维区域和检索 - 可变(前缀和)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。