Sum of Even Numbers After Queries
给一个数组和一堆query, 然后算数组中偶数的和. 分情况讨论
class Solution {
public int[] sumEvenAfterQueries(int[] A, int[][] queries) {
int[] res = new int[queries.length];
int tmp = 0;
for(int a : A){
if(a % 2 == 0)
tmp += a;
}
int d = 0;
for(int[] q : queries) {
int v = q[0]; // add value
int i = q[1]; // add value's index
int c = A[i]; // current value
if((c + v) % 2 == 0) { // if new value is even
if(c % 2 == 0) { // if current is even,
tmp += v; // just add value to current value
}
else { // if current is odd
tmp += c+v; // add sum
}
}
else { // important: if new value is odd
if(c % 2 == 0) { // and current is even
tmp -= c; // need to remove current from tmp sum
}
}
res[d++] = tmp;
A[i] += v;
}
return res;
}
}