LeetCode 985 Sum of Even Numbers After Queries 解题报告

时间:2022-02-28 16:58:36

题目要求

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.

题目分析及思路

题目给出一个整数数组A和一个query数组,query数组的每一个元素是一个列表,该列表由两个整数组成,分别对应一个值和一个A索引。要求把该值加到该索引对应的A数组的值,然后将A数组中的偶数求和。最后返回所有query对应的结果。首先对A中所有偶数求和,之后遍历query数组,判断某索引对应A中的值在加值前后的奇偶性。

python代码

class Solution:

def sumEvenAfterQueries(self, A: 'List[int]', queries: 'List[List[int]]') -> 'List[int]':

res = []

s = sum([i for i in A if i % 2 == 0])

for v, i in queries:

if A[i] % 2 == 0:

s -= A[i]

A[i] += v

if A[i] % 2 == 0:

s += A[i]

res.append(s)

return res