我必须编写一个接受整数数组作为参数的函数 并向用户显示“异常”数字。仅出现的数字 在一个整数而不是其余的整数中,然后对数组进行排序以便整数 具有最大出现的异常数字将被移动到第一个 数组的元素,然后是下一个整数 最大数量的不正确数字。
Input:
113
122
1000
Output:
There is 3 unusual digits:
0 occurs 3 times in 1000
2 occurs 2 times in 122
3 occurs 1 time in 113
Sorted:
1000
122
113
我的问题是如何检索与异常数字相关联的整数,以便将来对其进行排序?
我想知道哪个整数位0
来自它,以及它在整数中出现了多少次。
这是我到目前为止所做的,如果代码不好,我道歉。我不允许使用除iostream
以外的任何其他库,并且所有函数调用都必须自己编写。
#include <iostream>
using namespace std;
void getUncommon(int* iAry, int size) {
const int size2 = 10;
int* tmpAry = new int[size];
int totalCount[size2] = { 0 };
int currentCount[size2] = { 0 };
int totalUncommon = 0;
int i, j;
for (i = 0; i < size; i++) {
tmpAry[i] = iAry[i];
if (tmpAry[i] < 0)
tmpAry[i] *= -1;
for (j = 0; j < size2; j++)
currentCount[j] = 0;
if (tmpAry[i] == 0) {
currentCount[0] = 1;
}
while (tmpAry[i] / 10 != 0 || tmpAry[i] % 10 != 0){
currentCount[tmpAry[i] % 10] = 1;
tmpAry[i] /= 10;
}
for (j = 0; j < size2; j++) {
totalCount[j] += currentCount[j];
}
}
for (i = 0; i < size2; i++) {
if (totalCount[i] == 1) {
totalUncommon++;
}
}
cout << "Total of uncommon digits: " << totalUncommon << endl
<< "Uncommon digits:\n";
if (totalUncommon == 0) {
cout << "\nNo uncommon digits found.";
}
else {
for (i = 0; i < size2; i++) {
if (totalCount[i] == 1) {
cout << i << endl;
}
}
}
return;
}
int main(){
int* my_arry;
int size;
int i;
cout << "How many integers? ";
cin >> size;
my_arry = new int[size];
for (i = 0; i < size; i++) {
cout << "Enter value #" << i + 1 << " : ";
cin >> my_arry[i];
}
cout << "\nThe original array:" << endl;
for (i = 0; i < size; i++) {
cout << my_arry[i] << endl;
}
cout << "\nCalling function -\n" << endl;
getUncommon(my_arry, size);
delete[] my_arry;
return 0;
}
提前致谢。
答案 0 :(得分:1)
您可以使用数字0 1 2 ... 9 as the key
和键值对的pair of pointer to/index of integer containing the digit and number of occurrences of the digit in the integer as the value
创建地图。
开始迭代整数列表,从每个整数中提取数字及其出现次数。您可以通过使用模运算符或使用字符串函数(将整数转换为字符串后)来实现。 现在,对于每个整数,访问整数中所有数字的数字映射,如果该值未初始化,则使用指向此整数的指针/索引以及此整数中数字的出现次数更新该值。如果已填充地图条目,则表示它不是“异常”数字。因此,您可以使用标记来标记该地图条目,该标记表示此特定数字不是“不寻常”,因此无需更新此条目。
以这种方式迭代整个整数列表后,您可以迭代映射以找出哪些数字是异常的。您还可以从地图键值对的value
部分中的指针/索引访问包含的整数。您可以使用任何排序算法轻松地对这些条目进行排序(因为要排序的值的数量非常小,无需担心时间复杂度,请选择最简单的值)。