LeetCode260:Single Number III
阿新 • • 發佈:2018-12-12
Given an array of numbers nums
, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
Example:
Input:[1,2,1,3,2,5]
Output:[3,5]
Note:
- The order of the result is not important. So in the above example,
[5, 3]
- Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
LeetCode:連結
劍指offer同題:連結劍指Offer_程式設計題40:陣列中只出現一次的數字(異或)
我們還是從頭到尾一次異或陣列中的每一個數字,那麼最終得到的結果就是兩個只出現一次的陣列的異或結果。因為其他數字都出現了兩次,在異或中全部抵消了。由於兩個數字肯定不一樣,那麼異或的結果肯定不為0,也就是說這個結果陣列的二進位制表示至少有一個位為1。我們在結果陣列中找到第一個為1的位的位置,記為第n位
A和0異或的結果還是A。
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: List[int] """ remain, index = 0, 1 '''得到A和B異或的結果''' for num in nums: remain ^= num '''根據異或的結果找到從右往左的第一個1''' while remain & index == 0: index = index << 1 remain1, remain2 = 0, 0 '''分組判斷 必須判斷是否為0''' for num in nums: if num & index == 0: remain1 ^= num else: remain2 ^= num return [remain1, remain2]