给定一个长度为N的数列,求有多少个区间满足区间中出现最多的数的个数大于等于K?c++代码
时间: 2024-01-22 08:17:55 浏览: 44
以下是一个可行的 C++ 代码实现:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
vector<int> nums(n);
for (int i = 0; i < n; i++) {
cin >> nums[i];
}
int ans = 0;
for (int i = 0; i < n; i++) {
int j = i, maxCount = 0;
vector<int> count(10001, 0);
while (j < n) {
count[nums[j]]++;
maxCount = max(maxCount, count[nums[j]]);
if (maxCount >= k) {
ans += n - j;
break;
}
j++;
}
}
cout << ans << endl;
return 0;
}
```
思路如下:
- 对于每个起点 i,从 i 开始向右遍历数列,使用一个计数器 count 统计区间内每个数出现的次数。
- 同时记录当前区间内出现次数最多的数的出现次数 maxCount。
- 若 maxCount >= k,说明该区间满足条件,将 n - j(即以当前位置为起点的满足条件的区间数量)累加至答案中。
- 遍历结束后输出答案。
时间复杂度为 O(n^2),可以通过一些优化来加速,比如使用桶来统计每个数出现的次数。
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![hpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)