看板 Python 關於我們 聯絡資訊
Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Example 1: Input: [2,2,1] Output: 1 Example 2: Input: [4,1,2,1,2] Output: 4 這網站似乎會規定幾秒內跑完,所以在討論區可以看到各種大師的解法 最讓我不解的是,有人一行可以跑完這題.. 解法是這樣 class Solution(object): def singleNumber(self, nums): return reduce(lambda x, y: x^y,nums) 真的不懂啊啊啊 即使看過每一個函數關鍵字的作法(reduce,lambda,^) 都還是不懂... 有高手可以解釋嗎 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.24.135.202 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1535172973.A.57A.html
os653: 那函式套到 example1 做的計算是 (2 xor 2) xor 1 故輸出 1 08/25 13:16
mikapauli: 是說用int.__xor__不就好了 08/25 13:35
s860134: 簡單來說因為自己 xor 自己會等於 0 所以我只要 08/25 18:36
s860134: 從第一個 xor 到最後一個就會剩下題目中唯一沒有成雙的 08/25 18:36
s860134: 數字,他的單行解就是在做我上面三句 08/25 18:37
jlhc: 跟函數無關 就是做xor而已... 08/25 20:19
oToToT: xor特性,0^a=a而且a^a=0所以全部xor再一起就會是答案 08/25 20:23
alan23273850: smart problem! 08/25 21:44
Kyosuke: XOR = 不進位加法 08/26 22:28