力扣:136. 只出现一次的数字(Python3)

题目:

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

你必须设计并实现线性时间复杂度的算法来解决此问题,且该算法只使用常量额外空间。

来源:力扣(LeetCode)

链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

示例:

示例 1:

输入:nums = 2,2,1

输出:1

示例 2:

输入:nums = 4,1,2,1,2

输出:4

示例 3:

输入:nums = 1

输出:1

解法:

使用Counter记录每个数字出现的次数,返回值为1的键。

代码:

python 复制代码
from collections import Counter


class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        counter = Counter(nums)
        for k, v in counter.items():
            if v == 1:
                return k
相关推荐
JieE2124 小时前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
金銀銅鐵9 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1113 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0015 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵17 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf18 小时前
Agent 流程编排
后端·python·agent
copyer_xyf18 小时前
Agent RAG
后端·python·agent
copyer_xyf18 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf19 小时前
Agent 记忆管理
后端·python·agent