問題描述
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?
給定一個非空整數數組,每個元素出現兩次,只有一個元素例外。找到那一個。
注意:
你的算法應該具有線性運行時複雜度。你可以在不使用額外內存的情況下實現它嗎?
輸入: [2,2,1]
輸出: 1
輸入: [4,1,2,1,2]
輸出: 4
Python 實現
第一種方法:最直接的思路,使用計數器計算數組中每個元素出現的個數,返回僅出現一次的那個元素
(但是如果輸入數組很大的話,這種方法可能會消耗很多的額外內存)
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
cnt = {}
for num in nums:
if num in cnt:
cnt[num] += 1
else:
cnt[num] = 1
for num in cnt.keys():
if cnt[num] == 1:
return num
第二種方法:根據題目的意思,重複的元素只會出現兩次,剩下唯一的一個元素只出現一次,所以我們可以用一個列表來處理,重複出現的元素從列表中移除,最後剩下的必然是唯一的只出現一次的那個元素。
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
single = []
for num in nums:
if num in single:
single.remove(num)
else:
single.append(num)
return single[0]
第三種方法:思路和第二種相似,不過能夠避免使用額外的內存,就是使用 異或 運算,重複出現的元素經過兩次異或運算後相互抵消,於是最後的運算結果的值就是唯一的那個只出現一次的元素。
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ret = 0
for num in nums:
ret ^= num
return ret