LeetCode Biweekly Contest No. 81 (3/4)

本文解析了一道关于通过位操作最大化整数数组异或和的问题,介绍了解题思路:如何通过调整元素使其所有位上1的个数为奇数,最终目标是求得经过任意次数操作后的nums异或的最大值。核心思路是理解位运算原理并运用reduce和or_函数实现。
摘要由CSDN通过智能技术生成

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)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值