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
| class Solution { private: struct TreeNode{ int val, left, right; TreeNode() : val(0), left(-1), right(-1) {} }; vector<TreeNode> node; int judge(int k,int l,int r,vector<int>& arr){ int loc = node[k*2].right; if (loc-1>=l&&arr[loc]>arr[loc-1]&&arr[loc]>arr[loc+1]) return 1; if (loc+2<=r&&arr[loc+1]>arr[loc]&&arr[loc+1]>arr[loc+2]) return 1; return 0; } void update(int k,vector<int>& arr){ node[k].val = node[k*2].val + node[k*2+1].val + judge(k,node[k].left,node[k].right,arr); } void buildTree(int k,int l,int r,vector<int>& arr){ node[k].left = l; node[k].right = r; if(l==r) return; int mid = l + (r-l)/2; buildTree(k*2,l,mid,arr); buildTree(k*2+1,mid+1,r,arr); update(k, arr); } int queryAns(int k, int l,int r,vector<int>& arr){ if (l==node[k].left&&node[k].right==r) return node[k].val; int mid = node[k].left + (node[k].right-node[k].left)/2; int ans = 0; if (r<=mid) ans = queryAns(k*2,l,r,arr); else if (l>mid) ans = queryAns(k*2+1,l,r,arr); else ans = queryAns(k*2,l,mid,arr)+queryAns(k*2+1,mid+1,r,arr)+judge(k,l,r,arr); return ans; } void modify(int k,int index,int val,vector<int>& arr){ if(node[k].left == node[k].right && node[k].left == index) { arr[index] = val; return;} int mid = node[k].left + (node[k].right-node[k].left)/2; if(index<=mid) modify(k*2,index,val,arr); else modify(k*2+1,index,val,arr); update(k, arr); } public: Solution() : node(300005) {} vector<int> countOfPeaks(vector<int>& nums, vector<vector<int>>& queries) {
int root = 1, n = nums.size(); buildTree(root, 0, n-1, nums); vector<int> ans; for(auto query : queries){ if(query[0]==1) ans.push_back(queryAns(root, query[1], query[2], nums)); else modify(root, query[1], query[2], nums); } return ans; } };
|