如何根据不寻常数字的数量对数组进行排序
How to sort an array based on amount of unusual digits
我必须编写一个接受整数数组作为参数的函数并向用户显示"不寻常"的数字。只出现的数字在一个整数而不是其余的,然后排序数组,使整数出现次数最多的不寻常数字被移到第一个元素,然后后跟后跟下一个整数异常数字出现的最大次数。
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 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
部分的指针/索引访问包含整数。您可以使用任何排序算法(因为要排序的值的数量非常少,不需要担心时间复杂度,选择最简单的一个)根据出现值的数量对这些条目进行排序。
- 显示错误输出的简单数组排序程序
- C 使用单个函数对具有多种值类型的数组排序
- 2D数组排序,空格打乱顺序
- C 2D数组排序
- C++数组排序 - 将"bbba"和"0001"视为不正确排序的问题
- 数组排序功能
- CString 数组排序
- 简单的数组排序/检查 划分和征服版本
- C++ 中的多维数组排序
- 选择在++中对并行数组排序
- C++:二维指针数组排序:选择排序不适用于某些实例
- C++字符串数组排序
- C++中的指针数组排序算法
- 在VC++6中使用向量进行数组排序时出错,而在VC++2012中没有错误
- 将索引数组排序为主数组
- 数组排序、数组输入、数组输出
- C++数组排序,内存错误
- 在嵌入式系统上将数组排序功能从c++移植到c
- 基于其他int数组排序
- 多维数组排序c++奇怪行为