3.24剑指56-1, 56-2, 15 -- 56数组中数字出现的次数15二进制中1的个数

^按位异或 ,二进制位数不同结果位为1

从十进制看表现为相等的数异或为 0,不等的数异或不为0 。

注意:左移是a = a<<1,a<<1是错误的

 剑指 Offer 56 - I. 数组中数字出现的次数

一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。

class Solution:
    def singleNumbers(self, nums: List[int]) -> List[int]:
        if not nums:return[]
        x_yh_y = 0
        for num in nums:
            x_yh_y ^= num
        cur = 1
        while cur & x_yh_y == 0:
            cur <<= 1
        x, y = 0, 0
        for num in nums:
            if num & cur: x^=num
            else: y^=num
        return [x,y]

 总结一下位运算中异或可以用来去偶数个重复数字,与可以用来只取几位我们关注的

剑指 Offer 56 - II. 数组中数字出现的次数 II

就用hashmap好像挺好的,位运算的题解好复杂看不懂

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        if not nums:return
        dic = {}
        for num in nums:
            if num in dic:
                dic[num]+=1
            else:
                dic[num]=1
        for key in dic:
            if dic[key]==1:return key

剑指 Offer 15. 二进制中1的个数
 

逐位判断

 

class Solution:
    def hammingWeight(self, n: int) -> int:
        if not n:return 0
        cur = 1
        num = 0
        while cur<=n:
            if cur & n:
                num += 1
            cur = cur << 1
        return num

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值