**136. Single Number 只出现一次的数字
1. 原始题目
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,1] 输出: 1
示例 2:
输入: [4,1,2,1,2] 输出: 4
2. 解法
一道easy题目,解法非常亮眼,尤其是异或方法,全部摘自leetcode。
Approach 1: List operation
Algorithm
- Iterate over all the elements in \text{nums}nums
- If some number in \text{nums}nums is new to array, append it
- If some number is already in the array, remove it
1 class Solution(object):
2 def singleNumber(self, nums):
3 """
4 :type nums: List[int]
5 :rtype: int
6 """
7 no_duplicate_list = []
8 for i in nums:
9 if i not in no_duplicate_list:
10 no_duplicate_list.append(i)
11 else:
12 no_duplicate_list.remove(i)
13 return no_duplicate_list.pop()
Complexity Analysis
-
Time complexity : O(n^2)O(n2). We iterate through \text{nums}nums, taking O(n)O(n) time. We search the whole list to find whether there is duplicate number, taking O(n)O(n) time. Because search is in the
forloop, so we have to multiply both time complexities which is O(n^2)O(n2). -
Space complexity : O(n)O(n). We need a list of size nn to contain elements in \text{nums}nums.
Approach 2: Hash Table
Algorithm
We use hash table to avoid the O(n)O(n) time required for searching the elements.
- Iterate through all elements in \text{nums}nums
- Try if hash\_tablehash_table has the key for
pop - If not, set up key/value pair
- In the end, there is only one element in hash\_tablehash_table, so use
popitemto get it
1 class Solution(object):
2 def singleNumber(self, nums):
3 """
4 :type nums: List[int]
5 :rtype: int
6 """
7 hash_table = {}
8 for i in nums:
9 try:
10 hash_table.pop(i)
11 except:
12 hash_table[i] = 1
13 return hash_table.popitem()[0]
Complexity Analysis
-
Time complexity : O(n \cdot 1) = O(n)O(n⋅1)=O(n). Time complexity of
forloop is O(n)O(n). Time complexity of hash table(dictionary in python) operationpopis O(1)O(1). -
Space complexity : O(n)O(n). The space required by hash\_tablehash_table is equal to the number of elements in \text{nums}nums.
Approach 3: Math
Concept
2 * (a + b + c) - (a + a + b + b + c) = c2∗(a+b+c)−(a+a+b+b+c)=c
1 class Solution(object):
2 def singleNumber(self, nums):
3 """
4 :type nums: List[int]
5 :rtype: int
6 """
7 return 2 * sum(set(nums)) - sum(nums)
Complexity Analysis
-
Time complexity : O(n + n) = O(n)O(n+n)=O(n).
sumwill callnextto iterate through \text{nums}nums. We can see it assum(list(i, for i in nums))which means the time complexity is O(n)O(n) because of the number of elements(nn) in \text{nums}nums. -
Space complexity : O(n + n) = O(n)O(n+n)=O(n).
setneeds space for the elements innums
Approach 4: Bit Manipulation

class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = 0
for i in nums:
a ^= i
return a
Complexity Analysis
-
Time complexity : O(n)O(n). We only iterate through \text{nums}nums, so the time complexity is the number of elements in \text{nums}nums.
-
Space complexity : O(1)O(1).

浙公网安备 33010602011771号