[985] Sum of Even Numbers After Queries
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
Solution(TLC):
class Solution { public: vector<int> sumEvenAfterQueries(vector<int>& A, vector<vector<int>>& queries) { vector<int> vec;vec.clear(); for (auto row : queries) { if(row.size() == 2) { A[row[1]]+=row[0]; } int result = 0; for(auto item : A) { if(item % 2 == 0) { result +=item; } } vec.push_back(result); } return vec; } };
原本以为可以EZ水过的,结果成功超时,不出所料,简单题也有坑,算法的时间复杂度过高,看样子需要想一个简单算法,然后能力不足的我颤抖着打开了solution...
Solution(AC):
1 class Solution { 2 public: 3 vector<int> sumEvenAfterQueries(vector<int>& A, vector<vector<int>>& queries) 4 { 5 vector<int> vec;vec.clear(); 6 int result = 0; 7 for(int i : A) 8 { 9 if(i%2==0) 10 { 11 result+=i; 12 } 13 } 14 for(auto row : queries) 15 { 16 int val = row[0]; 17 int index = row[1]; 18 if(A[index] % 2 == 0) 19 result -=A[index]; 20 A[index] +=val; 21 if(A[index]%2 == 0) 22 result+=A[index]; 23 24 vec.push_back(result); 25 } 26 return vec; 27 28 }
思路解析:之前的暴力算法没必要每次查询就全部重新算一次,其实每次需要改变的就一个数字,也就是所谓的“增量更新”。
首先把原始所有的偶数全部求和,然后对查询位置上的数奇偶进行判断,如果是偶数则减去(后面会把查询后的结果返回),然后判断查询结果的奇偶,如果是偶数,则加到最终结果。
果然,偷瞄一时爽,一直偷瞄一直爽!感觉题目好坑。。但是这才是ez的题啊。