题目描述
给定一个 整数序列 a 以及2个整数x, k。求出有多少个区间[L, R] (L<=R),使得该区间中恰好有k个 (L<=i<= R) 满足
能被x整除。
补充说明 数据范围: length(a), x, k(1≤length(a), x<=,0≤k≤
)
序列 a 里的每个元素 (1 ≤
<
)。
输入:
[1,2,3,4],2,1
输出:
6
说明,总共有6个区间,满足恰好有1个数被2整除:[1,2], [1,2,3],[2,2],[2,3],[3,4],[4,4]。
思路
1. 使用滑动窗口,left记录区间开始,right记录区间末尾。
2. 当区间中整除x的元素数量count >= k时,需要再将right向右移动,移动到最后一个不满足a[right] %x == 0时结束,记录此时right移动的步数, 在code中是使用factor表示的。
3. 使用while循环让区间左边开始移动,left++, 当满足count == 0时,增加的区间数应该是factor
举例说明,基于给的样例,对于[1, 2], [1,2,3]来说,left从0移动到1,就产生了两种满足条件的区间: [2, 2]、[2,3]。
4. 直到count < k 内部while循环截止
代码
样例稀少,下面code可能缺少鲁棒性,欢迎大家讨论
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
using namespace std;
vector<int> parseArray(const string& str) {
vector<int> result;
stringstream ss(str.substr(1, str.size() - 4)); // 去掉首尾的方括号
string item;
while (getline(ss, item, ',')) {
result.push_back(stoi(item));
}
return result;
}
int main() {
string input;
getline(cin, input); // 读取一行输入
// 解析输入
vector<int> a = parseArray(input);
int x = input[input.size()-3] - '0';
int k = input[input.size()-1] - '0';
int count = 0; // 记录可以被x整除的数字的数量
int result = 0; // 记录满足条件的区间数量
int left = 0; // 滑动窗口的左边界
for (int right = 0; right < a.size();) {
if (a[right++] % x == 0) {
count++;
}
int factor = 1;
if (count == k)
{
result++;
while (a[right] % x != 0 && right < a.size())
{
result++;
right++;
factor++;
}
}
while (count == k) {
if (a[left++] % x == 0) {
count--;
}
if (count == k) {
result += factor;
}
}
}
cout << "result = " << result << endl;
return 0;
}