Leetcode 136. Single Number
题目
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
解法1:利用list
- 构建seen列表,碰到见过的num,移除seen中的该num
- 碰到未见过的num,加入到seen中
- 最后seen中只会剩下出现了一次的num
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
seen = []
for num in nums:
if num not in seen:
seen.append(num)
else:
seen.remove(num)
return seen[-1]
时间复杂度:O(n*n)
空间复杂度:O(n)
解法2:hash table
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
""