您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
#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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。