Leetcode 985. Sum of Even Numbers After Queries
目录
时间复杂度:O(N)
空间复杂度:O(1)
// Author: Tecker
// 176ms, 28.7MB; beat 96.40%, 100%
class Solution {
public:
vector<int> sumEvenAfterQueries(vector<int>& A, vector<vector<int> >& queries) {
vector<int> res(A.size(), 0);
int sum=0;
A[queries[0][1]]+=queries[0][0];
for(int &num : A) {
if (num%2==0) sum+=num;
}
res[0]=sum;
for(int i=1;i<queries.size();++i) {
int val=queries[i][0];
int idx=queries[i][1];
int tmp = A[idx];
A[idx]+=val;
if (isEven(tmp)) {
if (!isEven(A[idx]))
sum-=tmp;
else
sum+=val;
} else {
if (isEven(A[idx])) sum+=A[idx];
}
res[i]=sum;
}
return res;
}
private:
inline bool isEven(int a) {
return !(a & 1);
}
};
刚开始本来是想要用取模来做的,结果一不小心踩了大坑,以后要注意负数取模的正确计算方式
int mod(int x, int m) {
return (x%m + m)%m;
}
收获: 在不同的语言中,对负数执行取模运算,结果有可能会是不同的