解题思路:
把数据先输入,然后排序,再输出。
emmm...第一次用的vector容器做的,把题想复杂了,然后超时。
代码如下:
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstdio>
using namespace std;
int n;
struct shu
{
int a = 0, ci = 1;
};
bool cmp(shu a, shu b)
{
return a.a < b.a;
}
int main()
{
vector<shu> ans;
shu s;
cin >> n;
int i, o;
for (i = 0; i < n; ++i)
{
cin >> s.a;
ans.push_back(s);
}
sort(ans.begin(), ans.end(), cmp);
for (i = 1; i < ans.size(); ++i)
{
if (ans[i].a == ans[i - 1].a)
{
++ans[i - 1].ci;
ans.erase(ans.begin() + i);
--i;
}
}
for (i = 0; i < ans.size(); ++i) cout << ans[i].a << " " << ans[i].ci << endl;
return 0;
}
后来重新想一下把代码改进了一下:
#include<iostream>
#include<algorithm>
using namespace std;
int n, ans[200005], cnt = 1;
int main()
{
cin >> n;
int i, o;
for (i = 0; i < n; ++i) cin >> ans[i];
sort(ans, ans + n);
for (i = 0; i < n; ++i)
{
if (ans[i] == ans[i + 1]) ++cnt;
else {
cout << ans[i] << " " << cnt << endl;
cnt = 1;
}
}
return 0;
}
第一个代码最大数据用了1.2s以上,内存占用2.52MB,第二个代码只用了74ms,内存占用为1.16MB。
回头想想好搞笑哦