目录/Table of Content
第二十三天问:Single Number III
这次题目给出一个列表,列表中带有不同的整数,而只有两个整数只出现一次,其它都出现两次。然后,我们现在要找出那两个只出现一次的数字。
大家好,我是一个喜欢研究算法、机械学习和生物计算的小青年,我的CSDN博客是:一骑代码走天涯
如果您喜欢我的笔记,那么请点一下关注、点赞和收藏。如果內容有錯或者有改进的空间,也可以在评论让我知道。😄
题目&示例 (引用自 LeetCode)
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]
Notes:
- The order of the result is not important. So in the above example,
[5, 3]
is also correct. - Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
解题思路
我的方法不完全是按照题目笔记要求来算的。虽然时间复杂度是线性的,但是空间复杂度並不固定,而是会随着列表大小而变。
做法偏简单,只是单纯的把整个列表遍历一次,然后把数字放进一个 元素集 (set) 中,如果有重复就移除它。最后,剩下的就是答案。
代码
时间复杂度:O(
n
n
n)
空间复杂度:O(
n
n
n)
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
temp = set()
if len(nums) == 2:
return nums
for i in nums:
if i not in temp:
temp.add(i)
else:
temp.remove(i)
return list(temp)