985. Sum of Even Numbers After Queries
題目:給予一個陣列nums={n1, n2, n3} 和一個查詢陣列 queries,其中
queries[i] = [vali, indexi],queries[i] 表示一次「加總查詢」,將
vali加到 nums[indexi],並返回「nums偶數元素和」,求出i次queries時
每次的偶數元素和。
Example:
Input: nums = [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 nums[0], the array is [2,2,3,4], and the sum of even values
is 2 + 2 + 4 = 8.
After adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even
values is 2 + 4 = 6.
After adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even
values is -2 + 4 = 2.
After adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even
values is -2 + 6 = 4.
思路:
1. 先把nums的偶數元素和加總,令他為sum
2. 遍歷queries並維護sum的值
Java Code:
class Solution {
public int[] sumEvenAfterQueries(int[] nums, int[][] queries) {
int n = queries.length, sum = 0;
int[] res = new int[n];
for(int num : nums) {
if (num % 2 == 0)
sum += num;
}
for (int i = 0; i < n; i++) {
int tmp = nums[queries[i][1]];
nums[queries[i][1]] += queries[i][0];
if (nums[queries[i][1]] % 2 != 0)
sum -= tmp % 2 == 0 ? tmp : 0;
else
sum += tmp % 2 == 0 ? queries[i][0] : nums[queries[i][1]];
res[i] = sum;
}
return res;
}
}
今天又是個暴力解的一天 我好爛 = =