We have an array A
of integers, and an array queries
of queries.
For the i
-th query val = queries[i][0], index = queries[i][1]
, we add val to A[index]
. Then, the answer to the i
-th query is the sum of the even values of A
.
(Here, the given index = queries[i][1]
is a 0-based index, and each query permanently modifies the array A
.)
Return the answer to all queries. Your answer
array should have answer[i]
as the answer to the i
-th query.
Example 1:
Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
Output: [8,6,2,4]
Explanation:
At the beginning, the array is [1,2,3,4].
After adding 1 to A[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to A[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.
After adding -4 to A[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.
After adding 2 to A[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.
Note:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
1 <= queries.length <= 10000
-10000 <= queries[i][0] <= 10000
0 <= queries[i][1] < A.length
查询后的偶数和。
给出一个整数数组 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 次查询的答案。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-even-numbers-after-queries
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题不涉及算法,但是也不能就按暴力解做,我这里提供一个比暴力解稍快一些的做法。首先我们算出数组中所有偶数的和sum。接着开始遍历queries,对于每一个query涉及到的数字,如果原来这个数字就是偶数,我们可以先把他从sum中减去;如果这个数字在经过query操作后依然是偶数,我们再把它加回去。这样我们在整个代码里修改的都只有那些曾经是偶数或者是经过操作变成偶数的数字了,而不是所有的数字。
时间O(n)
空间O(n) - output
Java实现
1 class Solution { 2 public int[] sumEvenAfterQueries(int[] A, int[][] queries) { 3 int[] res = new int[queries.length]; 4 int sum = 0; 5 for (int i = 0; i < A.length; i++) { 6 if (((A[i] & 1) == 0)) { 7 sum += A[i]; 8 } 9 } 10 11 for (int i = 0; i < queries.length; i++) { 12 int val = queries[i][0]; 13 int index = queries[i][1]; 14 if ((A[index] & 1) == 0) { 15 sum -= A[index]; 16 } 17 A[index] = A[index] + val; 18 if ((A[index] & 1) == 0) { 19 sum += A[index]; 20 } 21 res[i] = sum; 22 } 23 return res; 24 } 25 }
JavaScript实现
1 /** 2 * @param {number[]} A 3 * @param {number[][]} queries 4 * @return {number[]} 5 */ 6 var sumEvenAfterQueries = function (A, queries) { 7 let res = []; 8 let sum = 0; 9 for (let num of A) { 10 if (num % 2 == 0) { 11 sum += num; 12 } 13 } 14 15 for (let query of queries) { 16 let val = query[0]; 17 let index = query[1]; 18 if ((A[index] & 1) == 0) { 19 sum -= A[index]; 20 } 21 A[index] = A[index] + val; 22 if ((A[index] & 1) == 0) { 23 sum += A[index]; 24 } 25 res.push(sum); 26 } 27 return res; 28 };