为了打印数组中元素的频率,我已经解决了一些打印问题.帮助解决



https://www.hackerrank.com/contests/cp-tutorial/challenges/cp-tutorial-11/problem

以下是我的解决方案,但我遇到的问题是,输出输出的语句与元素重复的次数完全相同,而不是每个不同的元素重复一次。有人能帮我吗?

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
int a[1000005];
for (int i = 0; i < n; i++)
cin >> a[i];
sort(a, a + n);
for (int j = 0; j < n; j++) {
int count = 0;
for (int k = 0; k < n; k++) {
if (a[j] == a[k]) {
count = count + 1;
}
}
if (count == 1) {
cout << a[j] << " appears once in the array." << 'n';
}
if (count > 1) {
cout << a[j] << " appears " << count << " times in the array." << 'n';
}
}
}

用这个替换最后两个if语句。我认为它应该起作用。

if (j + 1 == n || a[j] != a[j + 1]) {
cout << a[j] << " appears ";
if (count == 1)
cout << "once in the array.n";
else
cout << count << " times in the array.n";
}

更新:

您的算法当前为O(n^2(。我们可以利用这样一个事实,即在进行单次传递时对数组进行排序和计数:

sort(a, a + n);
int count = 0;
for (int j = 0; j < n; j++) {
count++;
if (j + 1 == n || a[j] != a[j + 1]) {
/* same code as above */
count = 0;
}
}

相关内容

最新更新