LeetCode 2401. Longest Nice Subarray(2025/3/18每日一题)

标题:Longest Nice Subarray

题目:

You are given an array nums consisting of positive integers.

We call a subarray of nums nice if the bitwise AND of every pair of elements that are in different positions in the subarray is equal to 0.

Return the length of the longest nice subarray.

subarray is a contiguous part of an array.

Note that subarrays of length 1 are always considered nice.

Example 1:

Input: nums = [1,3,8,48,10]
Output: 3
Explanation: The longest nice subarray is [3,8,48]. This subarray satisfies the conditions:
- 3 AND 8 = 0.
- 3 AND 48 = 0.
- 8 AND 48 = 0.
It can be proven that no longer nice subarray can be obtained, so we return 3.

Example 2:

Input: nums = [3,1,5,11,13]
Output: 1
Explanation: The length of the longest nice subarray is 1. Any subarray of length 1 can be chosen.

解题思路:求最大序列长度,要么用双指针,要么用DP。很显然这道题用双指针。几个整数的bitwise AND是0,换句话说就是转成二进制的值所有1都在不同位上。那我们用一个变量used_bits记录所有用过的比特位,用左指针“l”记录序列最左端,右指针"r"记录序列最右端。如果used_bits & nums[r] = 0,则更新最长序列,如果不等于0,则右移左指针。如何将右移呢?

这里有个小tip:

  • 在记录used_bits时,我们可以直接用并(|)操作,并且在记录之前需要先判断是否有bit 1 重叠。
  • 左指针右移时,需要将used_bits中左指针指向的数字对 bit 1 的贡献去掉。因为当前used_bits计算时所有数字都没有bit 1重叠的情况,因此只需要用一个 异或(^)操作即可去掉。

举个例子理解一下:264(0001 0000 1000),564(0010 0011 0100).记录used_bits: 264 | 564 = 828 (0011 0011 1100), 如果要去掉264对used_bits的贡献,只需要与264进行异或操作 828 ^ 264 = 564. 注意:通过异或操作来去掉数值的贡献值只适用于两数没有bit 1重叠的情况。

代码如下:

class Solution {
public:
    int longestNiceSubarray(vector<int>& nums) {
        int res = 1, l = 0, used_bits = 0;
        for(int r = 0; r < nums.size(); r++) {
            while ((used_bits & nums[r]) != 0) {
                used_bits ^= nums[l++];
            }
            used_bits |= nums[r];
            res = max(res, r - l + 1);
        }        
        return res;
    }
};

时间复杂度O(N),空间复杂度O(1).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值