力扣: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
相关推荐
用户8356290780511 小时前
无需 Office:Python 批量转换 PPT 为图片
后端·python
爱理财的程序媛3 小时前
openclaw 盯盘实践
算法
markfeng83 小时前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi4 小时前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee4 小时前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay4 小时前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤5 小时前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean6 小时前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽6 小时前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
MobotStone7 小时前
Google发布Nano Banana 2:更快更便宜,图片生成能力全面升级
算法