comments | difficulty | edit_url | tags | ||
---|---|---|---|---|---|
true |
中等 |
|
给出一个整数数组 A
和一个查询数组 queries
。
对于第 i
次查询,有 val = queries[i][0], index = queries[i][1]
,我们会把 val
加到 A[index]
上。然后,第 i
次查询的答案是 A
中偶数值的和。
(此处给定的 index = queries[i][1]
是从 0 开始的索引,每次查询都会永久修改数组 A
。)
返回所有查询的答案。你的答案应当以数组 answer
给出,answer[i]
为第 i
次查询的答案。
示例:
输入:A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]] 输出:[8,6,2,4] 解释: 开始时,数组为 [1,2,3,4]。 将 1 加到 A[0] 上之后,数组为 [2,2,3,4],偶数值之和为 2 + 2 + 4 = 8。 将 -3 加到 A[1] 上之后,数组为 [2,-1,3,4],偶数值之和为 2 + 4 = 6。 将 -4 加到 A[0] 上之后,数组为 [-2,-1,3,4],偶数值之和为 -2 + 4 = 2。 将 2 加到 A[3] 上之后,数组为 [-2,-1,3,6],偶数值之和为 -2 + 6 = 4。
提示:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
1 <= queries.length <= 10000
-10000 <= queries[i][0] <= 10000
0 <= queries[i][1] < A.length
我们用一个变量
对于每次查询
我们先判断
若
时间复杂度
class Solution:
def sumEvenAfterQueries(
self, nums: List[int], queries: List[List[int]]
) -> List[int]:
s = sum(x for x in nums if x % 2 == 0)
ans = []
for v, i in queries:
if nums[i] % 2 == 0:
s -= nums[i]
nums[i] += v
if nums[i] % 2 == 0:
s += nums[i]
ans.append(s)
return ans
class Solution {
public int[] sumEvenAfterQueries(int[] nums, int[][] queries) {
int s = 0;
for (int x : nums) {
if (x % 2 == 0) {
s += x;
}
}
int m = queries.length;
int[] ans = new int[m];
int k = 0;
for (var q : queries) {
int v = q[0], i = q[1];
if (nums[i] % 2 == 0) {
s -= nums[i];
}
nums[i] += v;
if (nums[i] % 2 == 0) {
s += nums[i];
}
ans[k++] = s;
}
return ans;
}
}
class Solution {
public:
vector<int> sumEvenAfterQueries(vector<int>& nums, vector<vector<int>>& queries) {
int s = 0;
for (int x : nums) {
if (x % 2 == 0) {
s += x;
}
}
vector<int> ans;
for (auto& q : queries) {
int v = q[0], i = q[1];
if (nums[i] % 2 == 0) {
s -= nums[i];
}
nums[i] += v;
if (nums[i] % 2 == 0) {
s += nums[i];
}
ans.push_back(s);
}
return ans;
}
};
func sumEvenAfterQueries(nums []int, queries [][]int) (ans []int) {
s := 0
for _, x := range nums {
if x%2 == 0 {
s += x
}
}
for _, q := range queries {
v, i := q[0], q[1]
if nums[i]%2 == 0 {
s -= nums[i]
}
nums[i] += v
if nums[i]%2 == 0 {
s += nums[i]
}
ans = append(ans, s)
}
return
}
function sumEvenAfterQueries(nums: number[], queries: number[][]): number[] {
let s = 0;
for (const x of nums) {
if (x % 2 === 0) {
s += x;
}
}
const ans: number[] = [];
for (const [v, i] of queries) {
if (nums[i] % 2 === 0) {
s -= nums[i];
}
nums[i] += v;
if (nums[i] % 2 === 0) {
s += nums[i];
}
ans.push(s);
}
return ans;
}
/**
* @param {number[]} nums
* @param {number[][]} queries
* @return {number[]}
*/
var sumEvenAfterQueries = function (nums, queries) {
let s = 0;
for (const x of nums) {
if (x % 2 === 0) {
s += x;
}
}
const ans = [];
for (const [v, i] of queries) {
if (nums[i] % 2 === 0) {
s -= nums[i];
}
nums[i] += v;
if (nums[i] % 2 === 0) {
s += nums[i];
}
ans.push(s);
}
return ans;
};