[LeetCode] 2419. Longest Subarray With Maximum Bitwise AND
You are given an integer array nums of size n.
Consider a non-empty subarray from nums that has the maximum possible bitwise AND.
In other words, let k be the maximum value of the bitwise AND of any subarray of nums. Then, only subarrays with a bitwise AND equal to k should be considered.
Return the length of the longest such subarray.
The bitwise AND of an array is the bitwise AND of all the numbers in it.
A subarray is a contiguous sequence of elements within an array.
Example 1:
Input: nums = [1,2,3,3,2,2]
Output: 2
Explanation:
The maximum possible bitwise AND of a subarray is 3.
The longest subarray with that value is [3,3], so we return 2.
Example 2:
Input: nums = [1,2,3,4]
Output: 1
Explanation:
The maximum possible bitwise AND of a subarray is 4.
The longest subarray with that value is [4], so we return 1.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 106
按位与最大的最长子数组。
给你一个长度为 n 的整数数组 nums 。考虑 nums 中进行 按位与(bitwise AND)运算得到的值 最大 的 非空 子数组。
换句话说,令 k 是 nums 任意 子数组执行按位与运算所能得到的最大值。那么,只需要考虑那些执行一次按位与运算后等于 k 的子数组。
返回满足要求的 最长 子数组的长度。数组的按位与就是对数组中的所有数字进行按位与运算。
子数组 是数组中的一个连续元素序列。
思路
这道题考察的是对位运算的敏感度吧我觉得。注意 AND 运算有一个特点,假如你有一个足够大的数字,比如 15 好了,他的二进制表达是 1111(四个 1)。如果 15 是数组里最大的数字,那么他跟任何其他数字做 AND 操作的结果都只会让结果变得更小,因为其他比 15 小的数字的二进制表达里面包含 0,与 15 AND 之后,结果只会比 15 更小。
所以这道题我们找到数组最大值 max 之后,需要判断连续的 max 到底有几个。最后返回最长的子数组的长度。
复杂度
时间O(n)
空间O(1)
代码
Java实现
class Solution { public int longestSubarray(int[] nums) { int max = 0, res = 0, cnt = 0; // First pass: find the maximum element for (int num : nums) { max = Math.max(max, num); } // Second pass: count the longest subarray of max elements for (int num : nums) { if (num == max) { cnt++; res = Math.max(res, cnt); } else { cnt = 0; // reset count when encountering a different element } } return res; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2021-09-15 [LeetCode] 1189. Maximum Number of Balloons