Leetcode 985. Sum of Even Numbers After Queries

2021-08-06 15:29:53 浏览数 (1)

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

1. Description

2. Solution

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

  • Version 1
代码语言:javascript复制
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/

0 人点赞