[leetcode]Single Number @ Python
原题地址:http://www.cnblogs.com/x1957/p/3373994.html
题意:Given an array of integers, every element appears twice except for one. Find that single one.
要求:线性时间复杂度,并且不用额外空间。
Logic: XOR will return 1 only on two different bits. So if two numbers are the same, XOR will return 0. Finally only one number left. A ^ A = 0 and A ^ B ^ A = B.
解题思路:这题考的是位操作。只需要使用异或(xor)操作就可以解决问题。异或操作的定义为:x ^ 0 = x; x ^ x = 0。用在这道题里面就是:y ^ x ^ x = y; x ^ x = 0; 举个例子:序列为:1122334556677。4是那个唯一的数,之前的数异或操作都清零了,之后的数:4 ^ 5 ^ 5 ^ 6 ^ 6 ^ 7 ^ 7 = 4 ^ ( 5 ^ 5 ^ 6 ^ 6 ^ 7 ^ 7 ) = 4 ^ 0 = 4。问题解决
class Solution: # @param A, a list of integer # @return an integer def singleNumber(self, A): ans = A[0] for i in range(1, len(A)): ans = ans ^ A[i] return ans
Challenge me - Shortest possible answer
class Solution: # @param A, a list of integer # @return an integer def singleNumber(self, A): return reduce(lambda x,y: x^y, A)
here is how reduce function works in Python: {The function reduce(func, seq) continually applies the function func() to the sequence seq. It returns a single value. } see diagram at http://www.python-course.eu/lambda.php
lambda x,y:x^y ----> this creates a function object that xors two arguments. just a short way of defining a function. For instance following is valid solution as well: { def singleNumber(self, A): return reduce(self.xor, A)
def xor(self, x,y): return x^y }
Refernce Source:
https://oj.leetcode.com/discuss/9396/challenge-me-shortest-possible-answer
http://www.cnblogs.com/zuoyuan/p/3719584.html