JZX轻语:简

LeetCode 985 - 查询后的偶数和

发表于2024年05月31日

#数组 #模拟

挺简单的数组题目,首先累加一下数组中的偶数和,然后对每个查询进行偶数和的更新即可:如果查询前的数为偶数,那么需要减去原数值,如果查询后的数为偶数,那么需要加上新数值。

class Solution:
    def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
        cur_even_sum = sum(num for num in nums if not num % 2)
        ans = []
        for diff, index in queries:
            old = nums[index]
            new = old + diff
            if not old % 2:
                cur_even_sum -= old
            if not new % 2:
                cur_even_sum += new
            nums[index] = new
            ans.append(cur_even_sum)
        return ans

闪念标签:LC

题目链接:https://leetcode.cn/problems/sum-of-even-numbers-after-queries/