算法知识点: 模拟,队列
复杂度:
解题思路:
这道题是让我们实现一个先进先出的缓存机制。
数据的存储:
由于是先进先出,所以我们可以用循环队列来维护缓存中的所有单词,这里可以用C++STL中的queue。
用bool数组存储每个单词是否已经在队列中,这样就可以用O(1)的时间判断每个单词是否已在缓存中了。
从前往后依次处理文章中的每个单词,然后分情况处理:
如果 x 已在缓存中,不需要做其他处理;
如果 x 不在缓存中:
如果队列不满,将 x 插入队尾;
如果队列已满,将队头弹出,然后将 x 插入队尾;
时间复杂度分析:
依次对每个单词处理一遍,每次处理时只有常数次操作,所以总时间复杂度是 ,其中 N 是单词个数。
C++ 代码
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std; const int N = 1010;
int n, m;
bool st[N];
int main()
{
cin >> m >> n;
int res = 0;
queue<int> q;
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
if (!st[x])
{
res++;
if (q.size() == m)
{
st[q.front()] = false;
q.pop();
}
q.push(x);
st[x] = true;
}
}
cout << res << endl;
return 0;
} 报名链接:https://www.nowcoder.com/courses/cover/live/248
使用优惠券免费报名:DCYxdCJ

京公网安备 11010502036488号