leetcode 985. Sum of Even Numbers After Queries( Python )

描述

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

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.ios

(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.app

Example 1:less

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:yii

1 <= A.length <= 10000
-10000 <= A[i] <= 10000
1 <= queries.length <= 10000
-10000 <= queries[i][0] <= 10000
0 <= queries[i][1] < A.length
複製代碼

解析

根據題意結合例子理解起來是比較簡單的,遍歷 queries 中的每一個子列表,在 A 中相應的位置上與子列表中的值相加,每次相加後記錄一次 A 中偶數的和便可得出結果。由於最後須要每次計算偶數總和,因此提早就計算了總和 S ,後面只須要在遍歷 queries 的時候判斷是奇數仍是偶數,在 S 上進行加減便可。時間複雜度爲 O(N+Q),N 和 Q 分別是 A 和 queries 的長度,空間複雜度爲 O(Q),儘管只分配了 O(1) 的額外空間。svg

解答

class Solution(object):
def sumEvenAfterQueries(self, A, queries):
    """
    :type A: List[int]
    :type queries: List[List[int]]
    :rtype: List[int]
    """
    S = sum(x for x in A if x % 2 == 0)
    ans = []

    for x, k in queries:
        if A[k] % 2 == 0: S -= A[k]
        A[k] += x
        if A[k] % 2 == 0: S += A[k]
        ans.append(S)

    return ans 
複製代碼

運行結果

Runtime: 448 ms, faster than 99.79% of Python online submissions for Sum of Even Numbers After Queries.
Memory Usage: 17.9 MB, less than 53.71% of Python online submissions for Sum of Even Numbers After Queries.
複製代碼

每日格言:每一個人都有屬於本身的一片森林,迷失的人迷失了,相逢的人會再相逢。ui

感謝支持
支付寶

支付寶

微信

微信
相關文章
相關標籤/搜索