LC.P985[查询后的偶数和]

方法一:模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int[] sumEvenAfterQueries(int[] nums, int[][] queries) {
int m = queries.length, sum = 0;
int[] ans = new int[m];
for (int num : nums) sum += num % 2 == 0 ? num : 0;
for (int i = 0; i < m; ++i) {
int val = queries[i][0], idx = queries[i][1];
if (nums[idx] % 2 == 0) sum -= nums[idx];
nums[idx] += val;
if (nums[idx] % 2 == 0) sum += nums[idx];
ans[i] = sum;
}
return ans;
}
}
  • 时间复杂度:$O(max(n, m))$
  • 空间复杂度:$O(1)$