[LeetCode in Python] 56 - I. (M) 数组中数字出现的次数

题目

https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/

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

示例 1:

输入:nums = [4,1,4,6]
输出:[1,6] 或 [6,1]
示例 2:

输入:nums = [1,2,10,4,1,4,3,3]
输出:[2,10] 或 [10,2]

限制:

2 <= nums <= 10000

解题思路

  • 先两两XOR,得到a^b=s
  • 再p=s&(-s),得到最低位的1
  • 既然该位为1,说明a和b在这一位不同,由此将数组分为两组,一组在这位是1,另一组是0
  • 划分的过程中就得到了a和b

代码

class Solution:
    def singleNumbers(self, nums: List[int]) -> List[int]:
        # - xor each other, get s=a^b
        s = reduce(lambda x,y:x^y, nums)
        
        # - get least 1, e.g. 0b1010 -> 0b10
        p = s & (-s)

        # - split nums into 2 parts, n&p==0 and n&p==1
        a, b = 0, 0
        for n in nums:
            if n & p:
                a ^= n
            else:
                b ^= n

        return [a,b]

猜你喜欢

转载自www.cnblogs.com/journeyonmyway/p/12791438.html