[问题] leetcode上看到的问题和解法不是很懂..

楼主: ponwar87123 (干我屁事喔北七)   2018-08-25 12:56:10
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,^)
都还是不懂...
有高手可以解释吗
作者: os653   2018-08-25 13:16:00
那函式套到 example1 做的计算是 (2 xor 2) xor 1 故输出 1
作者: mikapauli (桜花)   2018-08-25 13:35:00
是说用int.__xor__不就好了
作者: s860134 (s860134)   2018-08-25 18:36:00
简单来说因为自己 xor 自己会等于 0 所以我只要从第一个 xor 到最后一个就会剩下题目中唯一没有成双的数字,他的单行解就是在做我上面三句
作者: jlhc (H)   2018-08-25 20:19:00
跟函数无关 就是做xor而已...
作者: oToToT (屁孩)   2018-08-25 20:23:00
xor特性,0^a=a而且a^a=0所以全部xor再一起就会是答案
作者: alan23273850   2018-08-25 21:44:00
smart problem!
作者: Kyosuke (嚄咬阿雷雷咬阿雷)   2018-08-26 22:28:00
XOR = 不进位加法

Links booklink

Contact Us: admin [ a t ] ucptt.com