2401. Longest Nice Subarray - Medium
前往題目
想法
- 忘了有sliding window:D太久沒寫了
思路
關鍵是紀錄哪些bit
已經被使用,以及利用sliding window
鎖定範圍
Code
class Solution {
public int longestNiceSubarray(int[] nums) {
int usedBits = 0, l = 0, res = 0;
for (int r = 0; r < nums.length; ++r) {
// When not nice, shirnk until no conflict
while ((usedBits & nums[r]) != 0) {
// XOR to remove the left most element
usedBits ^= nums[l];
++l;
}
usedBits |= nums[r]; // Record used bits
res = Math.max(res, r - l + 1); // Update max value
}
return res;
}
}
2401. Longest Nice Subarray - Medium
https://f88083.github.io/2025/03/18/2401-Longest-Nice-Subarray-Medium/