Re: [闲聊] 每日LeetCode

楼主: Rushia (みけねこ的鼻屎)   2022-09-21 15:41:31
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;
}
}
今天又是个暴力解的一天 我好烂 = =
作者: jojobird7878 (jojo)   2022-09-21 15:44:00
讲人话
作者: lopp54321010 (嘻嘻010)   2022-09-21 15:46:00
我题目都看不懂 渍鲨了 谢谢喔
作者: Ericz7000 (Ericz7000nolan)   2022-09-21 15:50:00
挺直觉的啊 还可以更快喔?

Links booklink

Contact Us: admin [ a t ] ucptt.com