-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path206.h
More file actions
77 lines (71 loc) · 2.12 KB
/
206.h
File metadata and controls
77 lines (71 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Definition of Interval:
* classs Interval {
* int start, end;
* Interval(int start, int end) {
* this->start = start;
* this->end = end;
* }
*/
struct SegmentNode{
int start, end;
long long count;
SegmentNode *left, *right;
SegmentNode(int start, int end, long long count = 0){
this->start = start;
this->end = end;
this->count = count;
this->left = nullptr;
this->right = nullptr;
}
};
class Solution {
public:
/*
* @param A: An integer list
* @param queries: An query list
* @return: The result list
*/
vector<long long> intervalSum(vector<int> &A, vector<Interval> &queries) {
// write your code here
SegmentNode *root = build(0, A.size() - 1, A);
vector<long long> r;
for(int i = 0; i < queries.size(); i++){
r.push_back(query(root, queries[i].start, queries[i].end));
}
return r;
}
private:
SegmentNode *build(int start, int end, const vector<int> &A){
if(start == end){
return new SegmentNode(start, end, A[start]);
}
SegmentNode *root = new SegmentNode(start, end);
int mid = start + (end - start) / 2;
root->left = build(start, mid, A);
root->right= build(mid+1, end, A);
root->count= root->left->count + root->right->count;
return root;
}
long long query(SegmentNode *root, int start, int end){
if(root == nullptr) return 0;
if(start < root->start) start = root->start;
if(end > root->end) end = root->end;
if(root->start == start && root->end == end){
return root->count;
}
long long l = 0, r = 0;
int mid = root->start + (root->end - root->start) / 2;
if(start > mid){
r = query(root->right, start, end);
}
else if(end <= mid){
l = query(root->left, start, end);
}
else{
l = query(root->left, start, mid);
r = query(root->right,mid+1, end);
}
return l+ r;
}
};