《剑指offer》刷题系列——(五十四)数组中数字出现的次数 II

题目

在一个数组 nums 中除一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。

思路

这个题没有要求时间复杂度和空间复杂度,所以可以用哈希表。
python用字典结构实现。
如果该数字已经存在于字典中,就把value值加1,如果不存在,就以该数字为key存入字典。最后返回value为1的key值。

代码

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        dic={
    
    }
        for i in nums:
            if i in dic:
                dic[i]+=1
            else:
                dic[i]=1
        for i,j in dic.items():
            if j==1: return i

复杂度

时间复杂度是O(n)
空间复杂度是O(n)

猜你喜欢

转载自blog.csdn.net/weixin_44776894/article/details/107428093
今日推荐