985. Sum of Even Numbers After Queries
问题:
给定原数组A,和操作数组queries
假设q=queries[i]
那么q的操作为:对A[q[1]]+=q[0]
evensum为A的所有偶数元素之和,求每次操作后evensum的值,所组成的列表res
Example 1: Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]] Output: [8,6,2,4] Explanation: At the beginning, the array is [1,2,3,4]. After adding 1 to A[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8. After adding -3 to A[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6. After adding -4 to A[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2. After adding 2 to A[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4. Note: 1 <= A.length <= 10000 -10000 <= A[i] <= 10000 1 <= queries.length <= 10000 -10000 <= queries[i][0] <= 10000 0 <= queries[i][1] < A.length
解法:
先求的原数组的偶数和evensum
接着遍历操作数组queries
判断操作前A[q[1]]
若为偶数,evensum-=A[q[1]]
进行操作:A[q[1]]+=q[0]
再判断操作后的A[q[1]]
若为偶数,evensum+=A[q[1]]
把evensum放入结果数组res。
代码参考:
1 class Solution { 2 public: 3 vector<int> sumEvenAfterQueries(vector<int>& A, vector<vector<int>>& queries) { 4 vector<int> res; 5 int evensum=0; 6 for(int a:A){ 7 if(!(a%2))evensum+=a; 8 } 9 for(vector<int> q:queries){ 10 if(!(A[q[1]]%2)) evensum-=A[q[1]]; 11 A[q[1]]+=q[0]; 12 if(!(A[q[1]]%2)) evensum+=A[q[1]]; 13 res.push_back(evensum); 14 } 15 return res; 16 } 17 };
这里,也可以判断操作前A[q[1]]和要追加值q[0]的奇偶性
若为偶+偶,则evensum+=q[0]即可
偶+奇,则evensum-=A[q[1]]即可
奇+奇,则evensum+=(A[q[1]]+q[0])
奇+偶,不变化。
代码参考:
1 class Solution { 2 public: 3 vector<int> sumEvenAfterQueries(vector<int>& A, vector<vector<int>>& queries) { 4 vector<int> res; 5 int evensum=0; 6 for(int a:A){ 7 if(!(a%2))evensum+=a; 8 } 9 for(vector<int> q:queries){ 10 if(!(A[q[1]]%2)){//原数字为偶数 11 if(!(q[0]%2)){ 12 evensum+=q[0]; 13 }else{ 14 evensum-=A[q[1]]; 15 } 16 }else{//原数字为奇数 17 if(q[0]%2){ 18 evensum+=(A[q[1]]+q[0]); 19 } 20 } 21 res.push_back(evensum); 22 A[q[1]]+=q[0]; 23 } 24 return res; 25 } 26 };