美文网首页
Leetcode-Easy 985. Sum of Even N

Leetcode-Easy 985. Sum of Even N

作者: 致Great | 来源:发表于2019-02-17 15:25 被阅读11次

    题目描述

    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
    

    相关文章

      网友评论

          本文标题:Leetcode-Easy 985. Sum of Even N

          本文链接:https://www.haomeiwen.com/subject/zvpgeqtx.html