#include #include #include <unordered_map>

using namespace std;

int main() { int p, k; cin >> p; vector a(p); for (int i = 0; i < p; i++) { cin >> a[i]; } cin >> k; unordered_map<int, int> mp; //记录每个知识点最后出现的页数 int left = 0, right = 0; //双指针 int count = 0; //已经看过的知识点数 int res = p; //最少连续页数,初始化为p while (right < p) { mp[a[right]]++; //将右指针所指的知识点加入哈希表 if (mp[a[right]] == 1) { //如果这个知识点是第一次出现 count++; //已经看过的知识点数加1 } while (count == k) { //当看完k个知识点时 res = min(res, right - left + 1); //更新最少连续页数 mp[a[left]]--; //将左指针所指的知识点从哈希表中移除 if (mp[a[left]] == 0) { //如果这个知识点没有出现过了 count--; //已经看过的知识点数减1 } left++; //左指针右移 } right++; //右指针右移 } cout << res << endl; return 0; }

C++ 代码实现:教材最短连续页数求解

原文地址: https://www.cveoy.top/t/topic/opU9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录