Leetcode 985. Sum of Even Numbers After Queries

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

1. Description

Sum of Even Numbers After Queries

2. Solution

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

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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/
如果有收获,可以请我喝杯咖啡!