按位与运算在算法中的解法

tianyi Lv3

题目参考: https://leetcode.cn/problems/longest-subarray-with-maximum-bitwise-and/description/?envType=daily-question&envId=2025-07-30

题目

给你一个长度为 n 的整数数组 nums 。考虑 nums 中进行 按位与(bitwise AND)运算得到的值 最大 的 非空 子数组。换句话说,令 k 是 nums 任意 子数组执行按位与运算所能得到的最大值。那么,只需要考虑那些执行一次按位与运算后等于 k 的子数组。

  • 返回满足要求的 最长 子数组的长度。

  • 数组的按位与就是对数组中的所有数字进行按位与运算。

  • 子数组 是数组中的一个连续元素序列。

分析

AND(&)运算的性质是,参与 AND 运算的元素越多,AND 结果越小(不会变得更大)比如 3 & 2=2,3 & 2 & 1=0。所以我们通过 AND 运算能得到的最大值,就是 nums 的最大值 mx

  • 多个相同 mx 计算 AND,结果仍然是 mx;
  • 而 mx 与另一个小于 mx 的数计算 AND,结果会小于 mx。

所以问题变成:计算 nums 的最长连续子数组的长度,该子数组只包含 mx

解法

遍历即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
var longestSubarray = function(nums) {
const mx = Math.max(...nums);
let ans = 0, cnt = 0;
for (const x of nums) {
if (x === mx) {
cnt++;
ans = Math.max(ans, cnt);
} else {
cnt = 0; // 连续 mx 断开了,重新统计
}
}
return ans;
};
  • Title: 按位与运算在算法中的解法
  • Author: tianyi
  • Created at : 2025-07-30 09:47:40
  • Updated at : 2025-07-30 09:53:51
  • Link: https://github.com/ztygod/2025/07/30/按位与运算在算法中的解法/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
按位与运算在算法中的解法