LintCode_206 Interval Sum

Given an integer array (index from 0 to n-1, where n is the size of this array), and an query list. Each query has two integers[start, end]. For each query, calculate the sum number between index start and end in the given array, return the result list.

 Notice

We suggest you finish problem Segment Tree BuildSegment Tree Queryand Segment Tree Modify first.

Example

For array [1,2,7,8,5], and queries [(0,4),(1,2),(2,4)], return[23,9,20]

Challenge 

O(logN) time for each query


同样用线段树解决, 注意左闭右开:

/**
 * Definition of Interval:
 * classs Interval {
 *     int start, end;
 *     Interval(int start, int end) {
 *         this->start = start;
 *         this->end = end;
 *     }
 */
class Solution { 
public:
    /**
     *@param A, queries: Given an integer array and an query list
     *@return: The result list
     */
    vector<long long> intervalSum(vector<int> &A, vector<Interval> &queries) {
        // write your code here
        vector<long long> res;
        vector<long long> dat = init(A);
        for (int i = 0; i < queries.size(); i++) {
            long long sum = query(dat, queries[i].start, queries[i].end + 1, 
                                  0, 0, dat.size() / 2);
            res.push_back(sum);
        }
        return res;
    }
    vector<long long> init (vector<int>& A) {
        int len = A.size();
        int n = 1;
        while (n < len) {
            n *= 2;
        }
        vector<long long> dat(2 * n, 0);
        for (int i = 0; i < A.size(); i++) {
            update(dat, i , A[i]);
        }
        // int l = dat.size();
        // for (int i = 0; i < l; i++) {
        //     cout<<dat[i]<<" ";
        // }
        // cout<<""<<endl;
        return dat;
    }
    void update(vector<long long>& dat, int k, int value) {
        int n = dat.size() / 2;
        k += (n - 1);
        dat[k] = value;
        while ( k > 0) {
            k = (k - 1) / 2;
            dat[k]+=value;
        }
    }
    long long query(vector<long long>& dat, int a, int b, int k, int l, int r) {
        if (r <= a || b <= l) {
            return 0;
        }
        if (a <= l && r <= b) {
            return dat[k];
        } else {
            long long sum1 = query(dat, a, b, k * 2 + 1, l, (l + r) / 2);
            long long sum2 = query(dat, a, b, k * 2 + 2, (l + r) / 2, r);
            return sum1 + sum2;
        }
    }
};





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值