给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,3,2]
输出: 3
示例 2:
输入: [0,1,0,1,0,1,99]
输出: 99
法一:
利用数学公式:HashSet
将输入数组存储到 HashSet,然后使用 HashSet 中数字和的三倍与数组之和比较。
3 * (a + b + c) - (a + a + a + b + b + b + c) = 2 c
3×(a+b+c)−(a+a+a+b+b+b+c)=2c
class Solution:
def singleNumber(self, nums):
return (3 * sum(set(nums)) - sum(nums)) // 2
法二:位运算
使用位运算符可以实现O(1) 的空间复杂度。
XOR:该运算符用于检测出现奇数次的位:1、3、5 等。
为了区分出现一次的数字和出现三次的数字,使用两个位掩码:seen_once 和 seen_twice。
按位与运算符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0
按位取反运算符:对数据的每个二进制位取反,即把1变为0,把0变为1 。~x 类似于 -x-1 (优先级更高)
class Solution:
def singleNumber(self, nums: List[int]) -> int:
seen_once = seen_twice = 0
for num in nums:
# first appearance:
# add num to seen_once
# don't add to seen_twice because of presence in seen_once
# second appearance:
# remove num from seen_once
# add num to seen_twice
# third appearance:
# don't add to seen_once because of presence in seen_twice
# remove num from seen_twice
seen_once = ~seen_twice & (seen_once ^ num)
seen_twice = ~seen_once & (seen_twice ^ num)
return seen_once
另一种解题思路:
对于任意二进制位 xx ,有:
异或运算:x ^ 0 = x , x ^ 1 = ~x
与运算:x & 0 = 0 , x & 1 = x
class Solution:
def singleNumber(self, nums: List[int]) -> int:
ones, twos = 0, 0
for num in nums:
ones = ones ^ num & ~twos
twos = twos ^ num & ~ones
return ones
作者:jyd
链接:https://leetcode-cn.com/problems/single-number-ii/solution/single-number-ii-mo-ni-san-jin-zhi-fa-by-jin407891/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。