【力扣剑指 Offer 56 - I. 数组中数字出现的次数、数组中数字出现的次数 II】位运算+多解法

题目描述

数组中数字出现的次数1:
https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/
数组中数字出现的次数2:
https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-ii-lcof/

思路题解

数组中数字出现的次数1

https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/solution/jian-zhi-offer-56-i-shu-zu-zhong-shu-zi-tykom/

class Solution:
    def singleNumbers(self, nums: List[int]) -> List[int]:
        n,m,i,j=0,1,0,0
        for num in nums:n^=num
        while m&n==0:m<<=1
        for num in nums:
            if num&m:i^=num
            else:j^=num
        return i,j

在这里插入图片描述

数组中数字出现的次数2

自动状态机(不会)

https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-ii-lcof/solution/mian-shi-ti-56-ii-shu-zu-zhong-shu-zi-chu-xian-d-4/

位运算
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        counts=[0]*32
        for num in nums:
            for j in range(32):
                counts[j]+=num&1
                num>>=1
        res,m=0,3
        for i in range(32):
            res<<=1
            res|=counts[31-i]%m
        return res if counts[31]&m==0 else ~(res ^0xffffffff)
        
#举个例子           [              ]
# 位数 36 35 ... 32 31 30 29... 1 0
#      1  1  ... 1  1  0  1... 0 1
#   ^  0  0  ... 0  1  1  1... 1 1
#   =  1  1  ... 1  0  1  0... 1 0
#   ~  0  0  ... 0  1  0  1... 0 1

在这里插入图片描述

set

如 3 7 3 3
set(nums)→3 7
sum(set(nums)) * 3 → 3 3 3 7 7 7
sum(set(nums)) * 3 - sum(nums)→ 3 3
(sum(set(nums)) * 3 - sum(nums)) // 2→ 3

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        return (sum(set(nums)) * 3 - sum(nums)) // 2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值