leecode 解题总结:304. Range Sum Query 2D

来源:互联网 发布:南华模拟交易软件 编辑:程序博客网 时间:2024/05/18 01:35
#include <iostream>#include <stdio.h>#include <vector>#include <string>using namespace std;/*问题: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).Range Sum Query 2DThe 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) -> 8sumRegion(1, 1, 2, 2) -> 11sumRegion(1, 2, 2, 4) -> 12Note: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.分析:此题是求给定的矩阵中由左上角和右下角所划分的矩形中所有元素的和。仍然用long long。对于任意一个起点位置,遍历其终点位置时间复杂度为O(n^3),计算给定矩阵的和,时间复杂度为O(n^2)总的时间复杂度为O(n^5)。肯定不能这么做。如果我把每一行求出累加和,然后遍历矩阵中所求的每一行,总的时间复杂度为O(n^2)输入:5(行数) 5(列数) 3(给定的范围次数)3 0 1 4 25 6 3 2 11 2 0 1 54 1 0 1 71 0 3 0 52 1 4 31 1 2 2 1 2 2 4输出:81112关键:1 如果我把每一行求出累加和,然后遍历矩阵中所求的每一行,总的时间复杂度为O(n^2)*/class NumMatrix {public:    NumMatrix(vector<vector<int>> matrix) {        if(matrix.empty()){return;}int row = matrix.size();int col = matrix.at(0).size();for(int i = 0 ; i < row ; i++){vector<long long> sum;sum.push_back((long long)matrix.at(i).at(0));for(int j = 1 ; j < col ; j++){sum.push_back( sum.at(j-1) + (long long) matrix.at(i).at(j) );}_sums.push_back(sum);}    }        int sumRegion(int row1, int col1, int row2, int col2) {        if(_sums.empty()){return 0;}long long result = 0;//遍历每一行,计算每一行的值for(int i = row1 ; i <= row2 ; i++){if(col1 > 0){result += ( _sums.at(i).at(col2) -  _sums.at(i).at(col1 - 1) );}else{result += _sums.at(i).at(col2);}}return (int(result));    }private:vector<vector<long long> > _sums;};/** * Your NumMatrix object will be instantiated and called as such: * NumMatrix obj = new NumMatrix(matrix); * int param_1 = obj.sumRegion(row1,col1,row2,col2); */void print(vector<int>& result){if(result.empty()){cout << "no result" << endl;return;}int size = result.size();for(int i = 0 ; i < size ; i++){cout << result.at(i) << " " ;}cout << endl;}void process(){ vector<vector<int> > matrix; int value; int row; int col; int rangeTimes; int row1; int col1; int row2; int col2; while(cin >> row >> col >> rangeTimes ) { matrix.clear(); for(int i = 0 ; i < row ; i++) { vector<int> nums; for(int j = 0 ; j < col ; j++) { cin >> value; nums.push_back(value); } matrix.push_back(nums); } NumMatrix numMatrix(matrix); for(int i = 0 ; i < rangeTimes ; i++) { cin >> row1 >> col1 >> row2 >> col2;int result = numMatrix.sumRegion(row1 , col1 ,row2 , col2);cout << result << endl; } }}int main(int argc , char* argv[]){process();getchar();return 0;}

0 0
原创粉丝点击