Problem 3. 2317. Maximum XOR After Operations
题目描述:
You are given a 0-indexed integer array nums
. In one operation, select any non-negative integer x
and an index i
, then update nums[i]
to be equal to nums[i] AND (nums[i] XOR x)
.
Note that AND
is the bitwise AND operation and XOR
is the bitwise XOR operation.
Return the maximum possible bitwise XOR of all elements of nums
after applying the operation any number of times.
Example 1:
Input: nums = [3,2,4,6] Output: 7 Explanation: Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2. Now, nums = [3, 2, 4, 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7. It can be shown that 7 is the maximum possible bitwise XOR. Note that other operations may be used to achieve a bitwise XOR of 7.
Example 2:
Input: nums = [1,2,3,9,2] Output: 11 Explanation: Apply the operation zero times. The bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11. It can be shown that 11 is the maximum possible bitwise XOR.
Constraints:
1 <= nums.length <= 10^5
0 <= nums[i] <= 10^8
解题思路:
这个题比较唬人,题目给了一个operation,可以将nums中任何多个元素进行某种位操作,问经过若干操作之后,nums中所有数的异或的最大值是多少。
为什么说唬人呢?因为理论上,任取nums中的一个数a,给定一个数c满足a&c=c,即定义c是a的二进制子数,则总存在一个数b使得a对b经过该位操作变为数c,也就是a&(a^b)=c。
事实上,取b=a^c,则a&(a^b)=a&(a^a^c)=a&c=c。
于是,我们可以通过这种操作,让nums中每个元素n都变为n的所有二进制子数,比如5=(101)的二进制子数就包括(101)、(100)、(001)、(000)。
所以,我们可以通过这种变换,让nums的所有数,在每一个位上的1的个数都是奇数,这样就可以保证结果最大化。
而这正好是nums所有数进行或操作的结果。
class Solution:
def maximumXOR(self, nums: List[int]) -> int:
return reduce(or_, nums)
注意,or_实际上是operator这个库的函数,reduce则需要引入functools库
时间复杂度:O(N)
额外空间复杂度:O(1)