「只出现一次的数字」python之leetcode刷题|007

简介: 题目给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。说明:你的算法应该具有线性时间复杂度。

题目

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。

说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

示例 1:

输入: [2,2,3,2]
输出: 3
示例 2:
输入: [0,1,0,1,0,1,99]
输出: 99

解答

这道题是中等难度的题目,刚开始我一看,哎,这么简单,顺手就写了起来

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for i in nums:
            if nums.count(i) == 1:
                return i

运行一看也正确,没啥问题,统计数字嘛,以前也遇见过。
可是当我看运行结果我才知道,这道题不是不仅仅是解出来结果就行了。还要考虑时间复杂度。
看一下我的运行结果


img_ceb453b2d3f4537312d63e179bfbe2b8.png
执行结果

可以看到只打败了10%的提交者,虽然解决了问题,可耗时太长,显然不是这道题的最好解决方法。
看看大佬的代码

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 1:
            return nums[0]
        a = sorted(nums)
        for i in range(0,len(nums)-1):
            if a[i] == a[i-1] or a[i] == a[i+1]:
                continue
            else:
                return a[i]
        return a[-1]

之所以我的代码耗时时间长,是因为每次统计都要遍历一遍列表,大佬的代码只遍历了一次。
再看一个

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        buffer_dict = {x: 0 for x in nums}
        for x in nums:
            buffer_dict[x] += 1
        for x in buffer_dict.items():
            if x[1] == 1:
                return x[0]

利用字典来做,时间复杂度最小,耗时28ms,目前来说最好的解决方法。

目录
相关文章
|
2月前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
2月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
2月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3
|
2月前
|
容器
《LeetCode》——LeetCode刷题日记1
《LeetCode》——LeetCode刷题日记1
|
2月前
|
算法
LeetCode刷题---21.合并两个有序链表(双指针)
LeetCode刷题---21.合并两个有序链表(双指针)
|
2月前
|
算法
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
|
2月前
|
算法 测试技术
LeetCode刷题--- 430. 扁平化多级双向链表(深度优先搜索)
LeetCode刷题--- 430. 扁平化多级双向链表(深度优先搜索)
|
2月前
|
存储
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
144 38
|
11天前
|
API Python
[AIGC] 使用Python刷LeetCode:常用API及技巧指南
[AIGC] 使用Python刷LeetCode:常用API及技巧指南
|
13天前
刷题之Leetcode160题(超级详细)
刷题之Leetcode160题(超级详细)
13 0