给你一个整数数组 nums
,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 。请你找出并返回那个只出现了一次的元素。
示例 1:
输入:nums = [2,2,3,2]
输出:3
示例 2:
输入:nums = [0,1,0,1,0,1,100]
输出:100
提示:
1 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
nums 中,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次
进阶:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
【python 快速版】 直接使用python中自带统计某个元素在列表中的次数,其中有很多地方可以优化。
class Solution:
def singleNumber(self, nums: List[int]) -> int:
for ele in nums:
if nums.count(ele) == 1:
return ele
return -1
如果了解【python常用模块】collections 就很方便做。知识点温顾,总结放最后
class Solution:
def singleNumber(self, nums: List[int]) -> int:
fre = collections.Counter(nums) #主要生成一个字典,键为元素,值为元素个数。消耗内存
ans = [num for num ,occ in fre.items() if occ == 1][0] #遍历键值对,找到次数为1的元素
return ans
分析:时间复杂度 O(n) ;空间复杂度 O(n),哈希映射中包含最多 ⌊n/3⌋+1 个元素
【python知识点】
文档地址
collections --- 容器数据类型 — Python 3.8.13 文档https://docs.python.org/zh-cn/3.8/library/collections.html#collections.Counter.most_commonPython数据结构常用模块还有:heapq、operator、itertools