Re: [閒聊] 每日LeetCode

看板Marginalman作者 (みけねこ的鼻屎)時間1年前 (2022/09/21 15:41), 編輯推噓0(111)
留言3則, 3人參與, 1年前最新討論串4/719 (看更多)
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; } } 今天又是個暴力解的一天 我好爛 = = -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.231.23.40 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1663746094.A.1A7.html

09/21 15:44, 1年前 , 1F
講人話
09/21 15:44, 1F

09/21 15:46, 1年前 , 2F
我題目都看不懂 漬鯊了 謝謝喔
09/21 15:46, 2F

09/21 15:50, 1年前 , 3F
挺直覺的啊 還可以更快喔?
09/21 15:50, 3F
文章代碼(AID): #1ZAi0k6d (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1ZAi0k6d (Marginalman)