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

剑指 Offer 56 - I. 数组中数字出现的次数icon-default.png?t=M666https://leetcode.cn/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/
 

首先介绍异或的概念

异或_百度百科 (baidu.com)icon-default.png?t=M666https://baike.baidu.com/item/%E5%BC%82%E6%88%96/10993677?fr=aladdin 

暴力代码,采用字典的标记出现几次

class Solution:
    def singleNumbers(self, nums):
        dic={}
        res=[]
        for i in nums:
            dic[i]=0
        for i in nums:
            dic[i]+=1
        for i in nums:
            if dic[i]==1:
                res.append(i)
        return res

 

 

def singleNumber(self, nums: List[int]) -> List[int]:
    x = 0
    for num in nums:  # 1. 遍历 nums 执行异或运算
        x ^= num      
    return x;         # 2. 返回出现一次的数字 x

 

怎么把它们分成一个包含x,另一个包含y呢?

 

 

 

while z & m == 0: # m 循环左移一位,直到 z & m != 0
    m <<= 1

 

for num in nums:
    if num & m: x ^= num  # 若 num & m != 0 , 划分至子数组 1 ,执行遍历异或
    else: y ^= num        # 若 num & m == 0 , 划分至子数组 2 ,执行遍历异或
return x, y               # 遍历异或完毕,返回只出现一次的数字 x 和 y

  1. 返回值
  • 返回只出现一次的数字 x, y 即可。

 

class Solution:
    def singleNumbers(self, nums):
        z=0
        for i in nums:
            z^=i
        m=1
        while z&m==0:
            m<<=1
        x,y=0,0
        for i in nums:
            if i & m==0:
                x^=i
            else: y^=i
        return [x,y]

 

 

K神的返回值可能格式上有问题,K神返回的是x,y的元组 

 

 

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值