请帮我优化下面代码: ``` #include <iostream> #include <map> using namespace std; int lp = 1, rp = 1; int n, k; const int size = 1e8+5; int arr[100005]; map<int, int> box; int main() { cin >> n >> k; int mx = -1, mn = 1e9; for(int i = 1; i <= n; i++) { cin >> arr[i]; mx = max(mx, arr[i]); mn = min(mn, arr[i]); } int dif = 1, ans = 0, tl, tr; box[arr[1]] = 1; for(;rp != n;) { while(dif <= k + 1) { rp++; //cout << rp << "_" << arr[rp] << "_" << box[arr[rp]] << "_" << dif << endl; if(rp > n) break; box[arr[rp]]++; if(box[arr[rp]] == 1) dif++; } rp--; box[arr[rp + 1]]--; dif--; if(ans < (rp - lp + 1)) { tr = rp; tl = lp; ans = (rp - lp + 1); } //cout << lp << " " << rp << " " << ans << endl; while(dif == k + 1) { lp++; box[arr[lp - 1]]--; if(box[arr[lp - 1]] == 0) dif--; } } for(int i = mn; i <= mx; i++) { box[i] = 0; } mx = -1, mn = 1e9; for(int i = tl; i <= tr; i++) { box[arr[i]]++; mx = max(arr[i], mx); mn = min(arr[i], mn); } ans = 0; for(int i = mn; i <= mx; i++) { ans = max(ans, box[i]); } cout << ans << endl; return 0; } ···
时间: 2024-04-17 09:24:36 浏览: 110
#include <iostream> #include<iomanip> using namespace std;九九乘法表
下面是优化后的代码:
```cpp
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
int arr[100005];
for(int i = 1; i <= n; i++)
{
cin >> arr[i];
}
unordered_map<int, int> box;
int lp = 1, rp = 1;
int dif = 0, ans = 0, tl, tr;
while (rp <= n)
{
box[arr[rp]]++;
if (box[arr[rp]] == 1)
{
dif++;
}
if (dif <= k)
{
if (rp - lp + 1 > ans)
{
ans = rp - lp + 1;
tl = lp;
tr = rp;
}
rp++;
}
else
{
box[arr[lp]]--;
if (box[arr[lp]] == 0)
{
dif--;
}
lp++;
}
}
cout << ans << endl;
return 0;
}
```
这个优化的代码使用了unordered_map来替代map,因为unordered_map能够以O(1)的时间复杂度进行插入和查找操作,而map则是O(logn)的时间复杂度。另外,代码中去掉了一些不必要的变量和操作,使得代码更加简洁和高效。
阅读全文