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?
Example 1:
Input:[2,2,1]
Output:1
Example 2:
Input:[4,1,2,1,2]
Output:4
① sort and test by 2 steps each time. runs slightly slower than the last three approaches.
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
for i in range(0,len(nums),2):
if i+1>=len(nums) or nums[i]!=nums[i+1]:
return nums[i]
②same with the approach 1
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = []
for i in nums:
if i not in a:
a.append(i)
else:
a.remove(i)
return a[0]
③ use set to abstract all the different elements
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
aset = set(nums)
for i in aset:
nums.remove(i)
a = list(aset-set(nums))
return a[0]
Approach 1: List operation
Algorithm
Iterate over all the elements in nums
If some number in nums is new to array, append it
If some number is already in the array, remove it
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
no_duplicate_list = []
for i in nums:
if i not in no_duplicate_list:
no_duplicate_list.append(i)
else:
no_duplicate_list.remove(i)
return no_duplicate_list.pop()
Approach 2: Hash Table
Algorithm
We use hash table to avoid the O(n) time required for searching the elements.
Iterate through all elements in nums
Try if hash_table has the key for pop
If not, set up key/value pair
In the end, there is only one element in hash_table, so use popitem to get it
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
hash_table = {}
for i in nums:
try:
hash_table.pop(i)
except:
hash_table[i] = 1 #key-value:i-1
return hash_table.popitem()[0]
Approach 3: Math
Concept
2 * (a + b + c) - (a + a + b + b + c) = 2∗(a+b+c)−(a+a+b+b+c)=c
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return 2 * sum(set(nums)) - sum(nums)
Approach 4: Bit Manipulation
Concept
If we take XOR of zero and some bit, it will return that bit #异或
a⊕0=a
If we take XOR of two same bits, it will return 0
a⊕a=0
a⊕b⊕a=(a⊕a)⊕b=0⊕b=b
So we can XOR all bits together to find the unique number.
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = 0
for i in nums:
a ^= i
return a
i would say my sort solution is kind of a good answer.
hash table, try-except
math approach and XOR approach are brilliant!!!
网友评论