1. 程式人生 > >Leetcode 136:只出現一次的數字(最詳細的解法!!!)

Leetcode 136:只出現一次的數字(最詳細的解法!!!)

給定一個非空整數陣列,除了某個元素只出現一次以外,其餘每個元素均出現兩次。找出那個只出現了一次的元素。

說明:

你的演算法應該具有線性時間複雜度。 你可以不使用額外空間來實現嗎?

示例 1:

輸入: [2,2,1]
輸出: 1

示例 2:

輸入: [4,1,2,1,2]
輸出: 4

解題思路

相似問題

Leetcode 268:缺失數字(最詳細的解法!!!)

Leetcode 287:尋找重複數(最詳細的解法!!!)

直接使用Leetcode 268:缺失數字(最詳細的解法!!!)中的xor方法即可解決。

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

pythonic的寫法

from functools import reduce
from operator import xor
class Solution:
    def singleNumber
(self, nums): """ :type nums: List[int] :rtype: int """ return reduce(xor, nums)

reference:

https://leetcode.com/problems/single-number/discuss/43000/Python-different-solutions.

我將該問題的其他語言版本新增到了我的GitHub Leetcode

如有問題,希望大家指出!!!