【LEETCODE OJ】Single Number

Posted on 2014-04-07 02:12  卢泽尔  阅读(194)  评论(0)    收藏  举报

Prolbem link:

http://oj.leetcode.com/problems/single-number/

This prolbem can be solved by using XOR(exclusive OR) operation. Let x, y, and z be any numbers, and XOR has following properties:

  1. x XOR 0 is itself, i.e. x XOR 0 = 0;
  2. x XOR x is 0, i.e. x XOR x = 0;
  3. XOR is associative, i.e. (x XOR y) XOR z = x XOR (y XOR z).

So for list contains following (2m+1) numbers:

x0, x1, x1, x2, x2, ..., xm, xm.

If we XOR them together, according to the three properties above, we would obtain the result x0, which is just the single number the problem asks.

The following is my python solution accepted by oj.leetcode.

class Solution:
    # @param A, a list of integer
    # @return an integer
    def singleNumber(self, A):
        """
        We use exclusive OR operation for this problem.
        XOR has following two properties:
        1) Zero-Self. x XOR 0 = x for any number x
        2) Self-Zero. x XOR x = 0 for any number x
        3) XOR is associative. (x XOR y) XOR z = x XOR (y XOR z)
        Suppose A is consisiting of n numbers,
        x0, x1, x2, ..., xm, x1, x2, ..., xm (n = 2m + 1)
        Then we XOR them tegother, and by the associative property,
        we have the result as
        res = x0 XOR (x1 XOR x1) XOR (x2 XOR x2) XOR ... XOR (xm XOR xm).
        By Self-Zero property, res = x0 XOR 0 XOR ... XOR 0.
        By Zero-Self property, res = x0, it is just the single integer!
        """
        assert len(A)>0
        res = 0
        for n in A:
            res = res ^ n
        return res