【发布时间】:2019-06-17 05:54:15
【问题描述】:
我有这件骇人听闻的事情要做。 N 必须
输入格式:
9
42 42 34 26 42 35 34 47 47
输出:
42 3
34 2
47 2
26 1
35 1
#include <iostream>
#include <algorithm>
using namespace std;
struct ele
{
int count, index, val;
};
bool mycomp(struct ele a, struct ele b) {
return (a.val < b.val);
}
bool mycomp2(struct ele a, struct ele b) {
if (a.count != b.count) return (a.count < b.count);
else return a.index > b.index;
}
void sortByFrequency(int arr[], int n)
{
struct ele element[n];
for (int i = 0; i < n; i++)
{
element[i].index = i;
element[i].count = 0;
element[i].val = arr[i];
}
stable_sort(element, element + n, mycomp);
element[0].count = 1;
for (int i = 1; i < n; i++)
{
if (element[i].val == element[i - 1].val)
{
element[i].count += element[i - 1].count + 1;
element[i - 1].count = -1;
element[i].index = element[i - 1].index;
}
else element[i].count = 1;
}
stable_sort(element, element + n, mycomp2);
for (int i = n - 1, index = 0; i >= 0; i--)
if (element[i].count != -1)
for (int j = 0; j < element[i].count; j++)
arr[index++] = element[i].val;
}
int main() {
int n; cin >> n;
int* arr = new int[n];
int* seen = new int[n];
for (int i = 0; i < n; i++){
while(arr[i] < 20 || arr[i] > 50)
cin >> arr[i];
}
sortByFrequency(arr, n);
for (int i = 0; i < n; i++) {
if (seen[i] == 0) {
int count = 0;
for (int j = i; j < n; j++)
if (arr[j] == arr[i]) {
count += 1;
seen[j] = 1;
}
cout << arr[i] << " " << count << endl;
}
}
}
【问题讨论】:
-
但这不起作用。什么不起作用?出乎意料的输出?超过时间长度?输出看起来并没有那么糟糕。您可以只计算出现次数,而不是排序。要计算 [20, 50] 范围内的可能值,大小为 50 - 20 + 1 的数组就足够了。
-
我没有通过所有的测试用例。它们都被隐藏了。
-
不是很有帮助。你怎么知道应该改进什么?真烦人……
-
你可以使用
std::map。 -
当您不知道测试用例时,您必须自己发明。这是一个需要检查的案例:
n= 1,000,000。struct ele element[n];是一个可变长度数组。它们未包含在标准 C++ 中的原因之一是它们很容易导致堆栈溢出。ele可以是 24 字节长。您的n可能为 1,000,000。那是 24,000,000 字节的自动存储(通常是堆栈)。获得超过 10 MB 的自动存储空间是不常见的。幸运的是@Scheff 已经指出你不需要n频率。