注意这里的子数组是连续的非空的数组,我们要学会与处理就是求交集
class Solution {
public:
long long countSubarrays(vector<int>& nums, int k) {
long long ans = 0;
for (int i = 0; i < nums.size(); i++) {
int x = nums[i];
for (int j = i - 1; j >= 0 && (nums[j] & x) != nums[j]; j--) {
nums[j] &= x;
}
ans += upper_bound(nums.begin(), nums.begin() + i + 1, k) -
lower_bound(nums.begin(), nums.begin() + i + 1, k);
}
return ans;
}
};
class Solution {
public:
long long countSubarrays(vector<int>& nums, int k) {
long long ans = 0;
int left = 0, right = 0;
for (int i = 0; i < nums.size(); i++) {
int x = nums[i];
for (int j = i - 1; j >= 0 && (nums[j] & x) != nums[j]; j--) {
nums[j] &= x;
}
while (left <= i && nums[left] < k) {
left++;
}
while (right <= i && nums[right] <= k) {
right++;
}
ans += right - left;
}
return ans;
}
};
这种不会减少的边界就可以用指针来做