1. 程式人生 > >LeetCode 985 Sum of Even Numbers After Queries 解題報告

LeetCode 985 Sum of Even Numbers After Queries 解題報告

self mon 一個 val span class for return pan

題目要求

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

LeetCode 985 Sum of Even Numbers After Queries 解題報告