Re: [閒聊] 每日leetcode已回收

看板Marginalman作者 (早瀬ユウカの体操服 )時間1年前 (2024/04/29 09:35), 編輯推噓1(101)
留言2則, 2人參與, 1年前最新討論串168/1548 (看更多)
https://leetcode.com/problems/minimum-number-of-operations-to-make-array-xor-equal-to-k/description 2997. Minimum Number of Operations to Make Array XOR Equal to K 給你一個陣列nums和一個數字k,我們希望將每個數字xor起來之後等於k,你可以使用一 個操作翻轉任意數字的任一位元,求出最少要翻幾次。 思路: 1.假設 num1 ^ num2 ^ ... numn = x,我們希望 x == k 等價於 x ^ k == 0,所以我們 把 nums 的所有元素和 k 做 xor 然後看看翻轉幾個 1 可以令他為 0 即可。 pycode ------------------------------------------ class Solution: def minOperations(self, nums: List[int], k: int) -> int: for num in nums: k ^= num return bin(k).count('1') ------------------------------------------ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 101.138.217.240 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1714354557.A.F45.html

04/29 09:36, 1年前 , 1F
昨天才寫or版 我寫得超複雜 你寫得比較好
04/29 09:36, 1F

04/29 10:03, 1年前 , 2F
這題超簡單
04/29 10:03, 2F
文章代碼(AID): #1cBlbzz5 (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1cBlbzz5 (Marginalman)