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.
Example 1:
Note:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
1 <= queries.length <= 10000
-10000 <= queries[i][0] <= 10000
0 <= queries[i][1] < A.length
这题题目看上去有点迷,但看完栗子就清楚了要干嘛了。如果用brute force解,这个会是O(nk)的复杂度,因为每次操作都遍历一次,k次操作,遍历n个数。那么怎么优化呢?我们先算好一个偶数的sum,O(n)。然后每次操作,就根据这个数原先的奇偶来判断是否需要多evenTotal做修改。最后记得修改原数组,因为同一个位置可能改几遍。优化以后T:(n + k)
Last updated