href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
這是leetcode的第136題--Single Number
題目
Given an 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?
思路 如果直接用O(n2)會超時,想到用位運算異或XOR(^)就很簡單了,幾行代碼
show me the code
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ num = 0 for i in nums: num ^= i return num