Leetcode-Easy 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.

思路

新建一个列表,保留更新后的偶数值,将奇数值设为0,然后求和

代码实现

class Solution:
    def sumEvenAfterQueries(self, A: 'List[int]', queries: 'List[List[int]]') -> 'List[int]':
        new_A=[None]*len(A)
        even_index=[a if a%2==0 else 0 for a in A]
        for i in range(len(A)):
            val = queries[i][0]
            index = queries[i][1]
            A[index]+=val
            if A[index]%2==0:
                even_index[index]=A[index]
            else:
                even_index[index]=0
            new_A[i]=sum(even_index)
        return new_A
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值