一道编程题----按照元素出现次数对数组进行排序

问题描述:给定一个混乱的数组,根据该数组元素出现的次数进行排序,重复的元素排序后只出现一次,相同次数的元素的排序顺序与元素出现的次序相同。

输入:一个混乱的数组,每个数组元素以逗号隔开

输出:元素之间以空格隔开,元素按照出现的次数排序,次数相同的元素与出现的顺序相同。

例如:输入:3,2,2,1,3,2,4

          输出:2 3 1 4

注意:数组元素的个数不超过100

          每个元素的值也不超过100.

C++实现:

 1 #include <iostream>
 2 #include <string>
 3 #include <map>
 4 using namespace std;
 5 class MyCompare
 6 {
 7 public:
 8     bool operator()(int v1, int v2)const
 9     {
10         return v1 > v2;
11     }
12 };
13 
14 
15 int main()
16 {
17     int num[101] = { 0 };
18     int counts[101] = { 0 };
19     string str;
20     cin >> str;
21     // 分割字符串
22     int start = 0;
23     int end = str.length() - 1;
24     int i = 0; // 记录非重复元素个数
25     while (start <= end)
26     {
27         // 找到逗号的位置
28         int pos = str.find(',', start);
29         string tmp;
30         if (pos >= 0)
31         {
32             tmp = str.substr(start, pos - start);
33             start = pos + 1;
34             int tt = atoi(tmp.c_str());
35             // 去重
36             if (counts[tt] == 0 )
37             {
38                 num[i++] = tt;
39             }
40             // 统计次数
41             counts[tt] += 1;
42             tmp.clear();
43         }
44         else
45         {
46             // 找到尾部
47             tmp = str.substr(start, end - start + 1);
48             int tt  = atoi(tmp.c_str());
49             // 统计次数
50             if (counts[tt] == 0)
51             {
52                 num[i++] = tt;
53             }
54             counts[tt] += 1;
55             
56             tmp.clear();
57             break;
58         }    
59     }
60     // 去重后的数组
61     //for (int k = 0; k < i; k++)
62     //{
63     //    cout << num[k] << " ";
64     //}
65     //cout << endl;
66 
67     // key为次数 value为数值
68     multimap<int, int, MyCompare> myMap;
69     for (int j = 0; j < i; j++)
70     {
71         myMap.insert(make_pair(counts[num[j]], num[j]));
72     }
73     for (multimap<int,int, MyCompare>::iterator it = myMap.begin(); it != myMap.end(); it++)
74     {
75         cout << it->second << " ";
76     }
77     cout << endl;
78 
79     system("pause");
80     return 0;
81 }

 

个人实现的代码,希望网友批评指正。

 

posted @ 2020-10-29 15:58  AppLiu  阅读(665)  评论(0编辑  收藏  举报