Re: [闲聊] 每日LeetCode

楼主: yam276 ('_')   2022-09-22 16:12:43
※ 引述《Rushia (みけねこ的鼻屎)》之铭言:
: 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.
:
: 其实还可以 就是把 所有%2模运算改成 &1
: 时间从20ms(5.7%) ===> 3ms(100%)
class Solution
{
public:
vector<int> sumEvenAfterQueries(vector<int>& nums,
vector<vector<int>>& queries)
{
vector<int> output;
int total = 0;
for (int i = 0; i < nums.size(); i++)
{
int num = nums[i];
if (!(num & 1))
total += num;
}
for (auto& query : queries)
{
int before_num = nums[query[1]];
int after_num = nums[query[1]] + query[0];
if (!(before_num & 1))
total -= before_num;
if (!(after_num & 1 != 0))
total += after_num;
output.push_back(total);
nums[query[1]] = after_num;
}
return output;
}
};
好苦 因为C++题目给两个vector输入要你vector输出
所以效率被给纯阵列的Java屌打(我丢最快112ms/93.93%)
本来用两个if再加减效率太差
还是加入了主流先减再加
:(
作者: b0920075 (Void)   2022-09-22 17:41:00
leetcode c++ 跟 java 比通常都是被屌打,两个比较的基准不同

Links booklink

Contact Us: admin [ a t ] ucptt.com