美文网首页Leetcode
Leetcode 985. Sum of Even Number

Leetcode 985. Sum of Even Number

作者: SnailTyan | 来源:发表于2021-08-27 09:49 被阅读0次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Sum of Even Numbers After Queries

    2. Solution

    解析:Version 1,先对数组所有偶数求和,然后遍历查询,根据对应位置数字的奇偶性以及所加数字的奇偶性,来进行总和的加减操作并保存,最后需要更新对应位置的数值。

    • Version 1
    class Solution:
        def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
            total = 0
            result = []
            for i in range(len(nums)):
                if nums[i] % 2 == 0:
                    total += nums[i]
            for val, index in queries:
                if nums[index] % 2 == 0:
                    if val % 2 == 0:
                        total += val
                    else:
                        total -= nums[index]
                elif val % 2 == 1:
                        total += nums[index] + val
                result.append(total)
                nums[index] = nums[index] + val
            return result
    

    Reference

    1. https://leetcode.com/problems/sum-of-even-numbers-after-queries/

    相关文章

      网友评论

        本文标题:Leetcode 985. Sum of Even Number

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