Getting Runtime Error with the following Code. Any idea what am I missing here ?


  • 0
    K

    class NumArray {
    public:
    vector<int> segtree_sums;
    vector<int> values;

    NumArray(vector<int> &nums) {
        values.resize(nums.size());
        for(int i=0; i<nums.size(); i++){
            values[i] = nums[i];
        }
        segtree_sums.resize(2*nums.size());
        build(1, 0, nums.size()-1);
    }
    
    void update(int i, int val) {
        updateSegTree(1, 0, values.size()-1, i, val);
    }
    
    int sumRange(int i, int j) {
        return sumRangeSegTree(1, 0, values.size()-1, i, j);
    }
    
    void build(int node, int start, int end){
        if(start > end){
            return;
        }
        if(start == end){
            segtree_sums[node] = values[start];
            return;
        }
        int mid = start + (end- start)/2 ;
        build(2*node, start, mid);
        build(2*node + 1, mid+1, end);
        segtree_sums[node] = segtree_sums[2*node] + segtree_sums[2*node + 1];
    }
    
    int sumRangeSegTree(int node, int start, int end, int l, int r){
        
        if( start > end){
            return 0;
        }
    
        if(r < start || l > end){
            return 0;
        }
        
        if(start >= l && end <= r){
            return segtree_sums[node];
        }
        
        int mid = start + (end- start)/2;
        return sumRangeSegTree(2*node, start, mid, l, r) + sumRangeSegTree(2*node + 1, mid+1, end, l, r);
    }
    
    void updateSegTree(int node, int start, int end, int index, int val){
        
        if(start > end){
            return;
        }
        
        if (start == end){
            segtree_sums[node] = val;
            values[index] = val;
            return;
        }
        
        int mid = start + (end- start)/2;
        if(index >= start && index <= mid){
            updateSegTree(2*node, start, mid, index, val);
        }
        else{
            updateSegTree(2*node + 1, mid + 1, end, index, val);
        }
        
        segtree_sums[node] = segtree_sums[2*node] + segtree_sums[2*node + 1];
    }
    

    };

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


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.