LC 985. Sum of Even Numbers After Queries

Posted ethanhong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LC 985. Sum of Even Numbers After Queries相关的知识,希望对你有一定的参考价值。

We have an array A of integers, and an array queries of queries.

For the i-th query val = queries[i][0], index = queries[i][1], we add val to A[index].  Then, the answer to the i-th query is the sum of the even values of A.

(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 have answer[i] as the answer to the i-th query.

 

 

class Solution {
public:
  vector<int> sumEvenAfterQueries(vector<int>& A, vector<vector<int>>& queries) {
    int initval = 0;
    vector<int> ret;
    for(int v : A) {
      if(v % 2 == 0) initval += v;
    }
    for(auto v : queries) {
      int before = A[v[1]];
      A[v[1]] += v[0];
      if(before % 2 == 0) initval -= before;
      if(A[v[1]] % 2 == 0) initval += A[v[1]];
      ret.push_back(initval);
    }
    return ret;
  }
};

 

以上是关于LC 985. Sum of Even Numbers After Queries的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 985 Sum of Even Numbers After Queries ????????????

Leetcode 985. Sum of Even Numbers After Queries

leetcode985. Sum of Even Numbers After Queries

Leetcode_easy985. Sum of Even Numbers After Queries

Leetcode 985. Sum of Even Numbers After Queries

leetcode1315. Sum of Nodes with Even-Valued Grandparent