We have an array
A
of integers, and an arrayqueries
of queries.For the
i
-th queryval = queries[i][0], index = queries[i][1]
, we add val toA[index]
. Then, the answer to thei
-th query is the sum of the even values ofA
.(Here, the given index = queries[i][1] is a 0-based index, and each query permanently modifies the array A.)
Return the answer to all queries. Your
answer
array should haveanswer[i]
as the answer to thei
-th query.有两个数组A和queries,queries是个二维数组,第一个元素是值,第二个元素是索引,循环queries数组,把queries的每个值加到A数组对应索引位置上。求出每一次循环后A数组中的偶数和。
思路:先求出A数组中的偶数和。再循环queries数组,共四种情况:加运算之前是偶数,之后是奇数:总和-旧值;偶数-》偶数:总和+新值;奇数-》偶数:总和+旧值+新值;奇数-》奇数:总和不变。
class Solution {
public int[] sumEvenAfterQueries(int[] A, int[][] queries) {
int[] result = new int[queries.length];
int evenSum = 0;
for (int i1 : A) {
if (i1 % 2 == 0) {
evenSum += i1;
}
}
for (int i = 0; i < queries.length; i++) {
int index = queries[i][1];
int val = queries[i][0];
int old = A[index];
A[index] = A[index] + val;
if (old % 2 == 0 && A[index] % 2 != 0) {
result[i] = evenSum - old;
evenSum = result[i];
continue;
}
if (old % 2 == 0 && A[index] % 2 == 0) {
result[i] = evenSum + val;
evenSum = result[i];
continue;
}
if (old % 2 != 0 && A[index] % 2 == 0) {
result[i] = evenSum + old + val;
evenSum = result[i];
continue;
}
if (old % 2 != 0 && A[index] % 2 != 0) {
result[i] = evenSum;
evenSum = result[i];
}
}
return result;
}
}