1. 程式人生 > >leecode第二天-使用異或找出數組中的非重復元素

leecode第二天-使用異或找出數組中的非重復元素

leecode cep single integer put type json true readlines

leecode題目描述如下:
給定一個非空整數數組,除了某個元素只出現一次以外,其余每個元素均出現兩次。找出那個只出現了一次的元素。

思路:
最開始想到的是使用排序,排序之後就很容易找到非重復元素了。
後面看到網上有更巧妙的解決辦法,即使用異或來找出非重復元素,因為重復的元素經異或之後就互相抵消為0了,最後數組各個元素經過異或計算之後的結果就是那個唯一的非重復元素。

代碼:

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        num = 0
        for i in nums:
            num = num ^ i
        return num

def stringToIntegerList(input):
    return json.loads(input)

def intToString(input):
    if input is None:
        input = 0
    return str(input)

def main():
    import sys
    def readlines():
        for line in sys.stdin:
            yield line.strip(‘\n‘)
    lines = readlines()
    while True:
        try:
            line = lines.next()
            nums = stringToIntegerList(line)
            
            ret = Solution().singleNumber(nums)

            out = intToString(ret)
            print out
        except StopIteration:
            break

if __name__ == ‘__main__‘:
    main()

leecode第二天-使用異或找出數組中的非重復元素