# 解题报告：区间求和 I

http://www.lintcode.com/zh-cn/problem/interval-sum/
/**
* 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) {
SegmentTreeNode * root = build(0, A.size() - 1, A);

vector<long long>  d;
for (int i = 0; i<queries.size(); i++){
d.push_back(query(root, queries[i].start, queries[i].end));
}
return d;
}
SegmentTreeNode * build(int start, int end, vector<int> &A) {
if (start>end)return NULL;
int mid = start + (end - start) / 2;
if (start  == end)return new SegmentTreeNode(start, end, A[start] );
SegmentTreeNode *left = build(start, mid, A);
SegmentTreeNode *right = build(mid + 1, end, A);
SegmentTreeNode *stn = new SegmentTreeNode(start, end, left->max + right->max);
stn->left = left;
stn->right = right;
return stn;
}
unsigned int query(SegmentTreeNode *root, int start, int end) {
if (root == nullptr)return 0;
SegmentTreeNode *left = root->left, *right = root->right;
if (end<root->start)return 0;//end超出了最左
if (start>root->end)return 0;//start超出了最右
if (start<root->start)start = left->start;//start超出了最左
if (end>root->end)end = right->end;//end超出了最右
if (start == root->start&&end == root->end)return root->max;
if (left->end >= end){//完全左侧
return query(left, start, end);
}
if (right->start <= start){//完全右侧
return query(right, start, end);
}
return  query(left, start, left->end)+query(right, right->start, end);//左右之间都有
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：解题报告：区间求和 I 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)