如何根据不寻常数字的数量对数组进行排序

How to sort an array based on amount of unusual digits

本文关键字:数组 排序 何根 不寻常 数字      更新时间:2023-10-16

我必须编写一个接受整数数组作为参数的函数并向用户显示"不寻常"的数字。只出现的数字在一个整数而不是其余的,然后排序数组,使整数出现次数最多的不寻常数字被移到第一个元素,然后后跟后跟下一个整数异常数字出现的最大次数。

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部分的指针/索引访问包含整数。您可以使用任何排序算法(因为要排序的值的数量非常少,不需要担心时间复杂度,选择最简单的一个)根据出现值的数量对这些条目进行排序。