python3__leecode/0137. 只出现一次的数字 II

这篇博客详细介绍了LeetCode上的《单元素出现一次的数字II》问题,提供了五种解题方法,包括排序、哈希集、计数函数、HashMap和位运算。重点解析了位运算的解决方案,通过异或操作找到唯一出现一次的数字。适合想要提升算法能力的程序员阅读。
摘要由CSDN通过智能技术生成

一、刷题内容

原题链接

https://leetcode-cn.com/problems/single-number-ii/

内容描述

给你一个整数数组 nums ,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 。请你找出并返回那个只出现了一次的元素。

示例 1:
输入:nums = [2,2,3,2]
输出:3

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

提示:

1 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1

nums 中,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次

二、解题方案

1.方法一:排序

count函数(计数),index函数(查找序号),sort函数(计数)

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        nums.sort()
        p=0
        while p<len(nums):
            if nums.count(nums[p])==1:
                return nums[p]
            p+=3

2.方法二:Hashset

将输入数组存储到 HashSet,然后使用 HashSet 中数字和的三倍与数组之和比较。
3 × (a + b + c) - ( a + a + a + b + b + b + c) = 2c

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        return (3 * sum(set(nums)) - sum(nums)) // 2

3.方法三:count函数

利用集合中元素不重复的性质

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        a=set(nums)
        for i in a:
            if nums.count(i)==1:
                return i

4.方法四:HashMap

遍历输入数组,统计每个数字出现的次数,最后返回出现次数为 1 的数字。

from collections import Counter
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        hashmap = Counter(nums) 
        for k in hashmap.keys():
            if hashmap[k] == 1:
                return k

5.方法五:位运算

思路
仅当 twice 未变时,改变 once。
仅当 once 未变时,改变twice。
在这里插入图片描述

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        once = twice = 0
        for num in nums:
            once = ~twice & (once ^ num)
            twice = ~once & (twice ^ num)
        return once
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百里 Jess

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值