LeetCode 题解工作台

按位与最大的最长子数组

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

category

3

题型

code_blocks

9

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·结合·位运算·操作

bolt

答案摘要

由于按位与的操作,不会使得数字变大,因此最大值就是数组中的最大值。 题目可以转换为求最大值在数组中最多连续出现的次数。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·结合·位运算·操作 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个长度为 n 的整数数组 nums

考虑 nums 中进行 按位与(bitwise AND)运算得到的值 最大非空 子数组。

  • 换句话说,令 knums 任意 子数组执行按位与运算所能得到的最大值。那么,只需要考虑那些执行一次按位与运算后等于 k 的子数组。

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

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

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

 

示例 1:

输入:nums = [1,2,3,3,2,2]
输出:2
解释:
子数组按位与运算的最大值是 3 。
能得到此结果的最长子数组是 [3,3],所以返回 2 。

示例 2:

输入:nums = [1,2,3,4]
输出:1
解释:
子数组按位与运算的最大值是 4 。 
能得到此结果的最长子数组是 [4],所以返回 1 。

 

提示:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 106
lightbulb

解题思路

方法一:脑筋急转弯

由于按位与的操作,不会使得数字变大,因此最大值就是数组中的最大值。

题目可以转换为求最大值在数组中最多连续出现的次数。

我们先遍历数组 nums\textit{nums} 找到最大值 mx\textit{mx},然后再遍历数组一次,找到最大值连续出现的次数,最后返回这个次数即可。

时间复杂度 O(n)O(n),其中 nn 是数组 nums\textit{nums} 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def longestSubarray(self, nums: List[int]) -> int:
        mx = max(nums)
        ans = cnt = 0
        for x in nums:
            if x == mx:
                cnt += 1
                ans = max(ans, cnt)
            else:
                cnt = 0
        return ans
speed

复杂度分析

指标
时间complexity is O(N) for a single pass to find maximum and scan subarrays. Space complexity is O(1) since only counters are maintained, no extra structures.
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect recognition that bitwise AND is maximized by the largest single number.

  • question_mark

    Look for O(N) single-pass solutions avoiding nested loops.

  • question_mark

    Check if candidate counts consecutive maximum elements correctly.

warning

常见陷阱

外企场景
  • error

    Confusing bitwise AND logic and trying to AND all subarrays explicitly.

  • error

    Using extra arrays or sets, which increases space unnecessarily.

  • error

    Failing to reset the consecutive count when a smaller element appears.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Find longest subarray with minimum bitwise OR instead of AND.

  • arrow_right_alt

    Determine the longest subarray where all elements are equal to a given target.

  • arrow_right_alt

    Count the number of subarrays achieving the maximum bitwise AND instead of the longest length.

help

常见问题

外企场景

按位与最大的最长子数组题解:数组·结合·位运算·操作 | LeetCode #2419 中等