leetcode@ [303/304] Range Sum Query - Immutable / Range Sum Query 2D - Immutable

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

class NumArray {

public: vector<int> vec;
public:
    NumArray(vector<int> &nums) {
        if(nums.empty()) return;
        else {
            vec.push_back(nums[0]);
            for(int i=1;i<nums.size();++i) vec.push_back(vec[i-1] + nums[i]);
        }
    }

    int sumRange(int i, int j) {
        if(i<0 || j>=vec.size()) return 0;
        if(i==0) return vec[j];
        else return vec[j] - vec[i-1];
    }
};


// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
View Code

 

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

class NumMatrix {
public:
    vector<vector<int>> vec;
    NumMatrix(vector<vector<int>> &matrix) {
        if(matrix.size() == 0 || matrix[0].size() == 0) return;
        vec.resize(matrix.size());
        for(int i=0;i<vec.size();++i) vec[i].resize(matrix[0].size());
        
        vec[0][0] = matrix[0][0];
        for(int col=1;col<vec[0].size();++col) vec[0][col] = matrix[0][col] + vec[0][col-1];
        
        for(int row=1;row<vec.size();++row) {
            for(int col=0;col<vec[row].size();++col) {
                if(col == 0) vec[row][col] = matrix[row][col];
                else vec[row][col] = matrix[row][col] + vec[row][col-1];
            }
        }
        
        for(int row=1;row<vec.size();++row) {
            for(int col=0;col<vec[row].size();++col) {
                vec[row][col] += vec[row-1][col];
            }
        }
        
        for(int i=0;i<vec.size();++i) {
            for(int j=0;j<vec[i].size();++j) cout<<vec[i][j]<<" ";
            cout<<endl;
        }
    }
    int sumRegion(int row1, int col1, int row2, int col2) {
        if(row1<0 || row2>=vec.size() || col1<0 || col2>=vec[0].size()) return 0;
    
        int leftTop = 0;
        if(row1 == 0 || col1 == 0) leftTop = 0;
        else if(row1 && col1) leftTop = vec[row1-1][col1-1];
        
        int ret1 = 0;
        if(row1 == 0) ret1 = vec[row2][col2];
        else if(row1 > 0) ret1 = vec[row2][col2] - vec[row1-1][col2];
        
        int ret2 = 0;
        if(col1 == 0) ret2 = ret1;
        else if(col1 > 0) ret2 = ret1 - vec[row2][col1-1] + leftTop;
        
        return ret2;
    }
};


// Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.sumRegion(1, 2, 3, 4);
View Code

 

posted @ 2015-11-12 19:20  流白  阅读(271)  评论(0编辑  收藏  举报