您好,登錄后才能下訂單哦!
#include <vector>
#include <iostream>
class Array {
public:
Array(const std::vector<int>& nums) {
data = nums;
buildSegmentTree(0, data.size() - 1, 0);
}
int query(int start, int end) {
return queryHelper(start, end, 0, data.size() - 1, 0);
}
private:
std::vector<int> data;
std::vector<int> segmentTree;
void buildSegmentTree(int start, int end, int index) {
if (start == end) {
segmentTree[index] = data[start];
return;
}
int mid = start + (end - start) / 2;
buildSegmentTree(start, mid, 2 * index + 1);
buildSegmentTree(mid + 1, end, 2 * index + 2);
segmentTree[index] = segmentTree[2 * index + 1] + segmentTree[2 * index + 2];
}
int queryHelper(int queryStart, int queryEnd, int start, int end, int index) {
if (queryStart <= start && queryEnd >= end) {
return segmentTree[index];
}
if (queryStart > end || queryEnd < start) {
return 0;
}
int mid = start + (end - start) / 2;
return queryHelper(queryStart, queryEnd, start, mid, 2 * index + 1) +
queryHelper(queryStart, queryEnd, mid + 1, end, 2 * index + 2);
}
};
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5, 6, 7};
Array arr(nums);
int sum = arr.query(1, 4);
std::cout << sum << std::endl;
return 0;
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。