先看一下最后一题,这是一个树状数组的题目,那就水一下吧,但是由于没有注意问题,wa了很多次
cpp
const int N = (int)1e5 + 5;
int n;
int flag[N];
int dp[N];
class Solution {
public:
vector<int> countOfPeaks(vector<int>& nums, vector<vector<int>>& queries) {
n = nums.size();
memset(dp,0,sizeof dp);
memset(flag,0,sizeof flag);
vector<int> ans;
for (int i = 1; i < n - 1; i++) {
if (nums[i] > nums[i + 1] && nums[i] > nums[i - 1]) {
flag[i + 1] = 1;
add(i + 1, 1);
}
}
// for (int i = 1; i <= n; i++) {
// cout << i << " " << find(i) - find(i - 1) << endl;
// }
for (int i = 0; i < queries.size(); i++) {
if (queries[i][0] == 2) {
int index = queries[i][1], val = queries[i][2];
nums[index] = val;
fun(index, nums); fun(index - 1, nums); fun(index + 1, nums);
// for (int i = 1; i <= n; i++) {
// cout << i << " " << find(i) - find(i - 1) << endl;
// }
}
else {
//ans.push_back(find(queries[i][2]) - find(queries[i][1] + 2));
int temp = find(queries[i][2] + 1) - find(queries[i][1]);
if (flag[queries[i][2] + 1]) temp--;
if (flag[queries[i][1] + 1]) temp--;
ans.push_back(temp>0?temp:0);
}
}
return ans;
}
int lowbit(int x) {
return x & (-x);
}
void add(int x, int p) {
for (int i = x; i <= n; i += lowbit(i)) {
dp[i] += p;
}
}
int find(int x) {
if (x == 0) return 0;
return dp[x] + find(x - lowbit(x));
}
void fun(int index, vector<int>& nums) {
if (index <= 0 || index >= (n - 1)) return;
if (nums[index] > nums[index + 1] && nums[index] > nums[index - 1]) {
if (flag[index + 1]) return;
add(index + 1, 1), flag[index + 1] = 1;
}
else {
if (!flag[index + 1]) return;
add(index + 1, -1), flag[index + 1] = 0;
}
}
};