【Python3】 LeetCode 7月挑战题目之23 - Single Number III

第二十三天问: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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值