作者yam276 (博衣こより的貓)
看板Marginalman
標題Re: [閒聊] 每日LeetCode
時間Thu Sep 22 16:12:43 2022
※ 引述《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再加減效率太差
還是加入了主流先減再加
:(
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.248.143.172 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1663834365.A.FF6.html
推 b0920075: leetcode c++ 跟 java 比通常都是被屌打,兩個比較的基 09/22 17:41
→ b0920075: 準不同 09/22 17:41