leetcode(35)位运算系列题目
不需要额外空间的方法,就往位运算上想
136. 只出现一次的数字
异或运算的性质:
1.交换律:a ^ b ^ c <=> a ^ c ^ b
2.任何数于0异或为任何数 0 ^ n => n
3.相同的数异或为0: n ^ n => 0
a = [2,3,2,4,4]
2 ^ 3 ^ 2 ^ 4 ^ 4等价于 2 ^ 2 ^ 4 ^ 4 ^ 3 => 0 ^ 0 ^3 => 3
class Solution:
def singleNumber(self, nums: List[int]) -> int:
a = 0
for n in nums:
a ^= n
return a
137. 只出现一次的数字 II
class Solution:
def singleNumber(self, nums: List[int]) -> int:
one, two = 0, 0
for n in nums:
one = one ^ n & ~ two
two = two ^ n & ~ one
return one
260. 只出现一次的数字 III
重复题目剑指 Offer 56 - I. 数组中数字出现的次数
805. 数组的均值分割
使用「二进制枚举」来做,用二进制表示中的 0 和 1 分别代表在划分数组两边。
class Solution:
def splitArraySameAverage(self, nums: List[int]) -> bool:
n = len(nums)
if n == 1:return False
s = sum(nums)
m = n // 2
for i, v in enumerate(nums):
nums[i] = v * n - s
l = set()
for i in range(1, 1 << m):
tol = sum(v for j, v in enumerate(nums[:m]) if i >> j & 1)
if tol == 0:
return True
l.add(tol)
r_sum = sum(nums[m:])
for i in range(1, 1 << (n - m)):
tol = sum(v for j, v in enumerate(nums[m:]) if i >> j & 1)
if tol == 0 or tol != r_sum and -tol in l:
return True
return False