🎈 作者:Linux猿
🎈 简介:CSDN博客专家🏆,华为云享专家🏆,Linux、C/C++、云计算、物联网、面试、刷题、算法尽管咨询我,关注我,有问题私聊!
🎈 关注专栏: 数据结构和算法成神路【精讲】优质好文持续更新中……🚀🚀🚀
🎈 欢迎小伙伴们点赞👍、收藏⭐、留言💬
目录
一、题目描述
1.1 输入描述
1.2 输出描述
1.3 测试样例
1.3.1 示例 1
二、解题思路
三、代码实现
四、时间复杂度

一、题目描述
给定一个乱序的数组,删除所有的重复元素,使得每个元素只出现一次,并且按照出现的次数从高到低进行排序,相同出现次数按照第一次出现顺序进行先后排序。
1.1 输入描述
一个数组。
1.2 输出描述
去重排序后的数组。
1.3 测试样例
1.3.1 示例 1
输入
1, 3, 3, 3, 2, 4, 4, 4, 5 
输出
3, 4, 1, 2, 5 
备注:数组大小不超过100, 数组元素值不超过100
二、解题思路
本题比较简单,主要考查对 sort 排序的理解,解题步骤如下所示。
(1)首先,解析输入的数据,将数据存储到一个 Node 结构中,Node 结构包括 value (值)、idx (原下标)、num(个数);
(2)将所有的 Node 数据排序,首先根据 num 个数排序,如果 num 相等,则根据 idx 小的排到前面;
(3)最后,输出排序后 value 的值;
三、代码实现
代码实现如下所示。
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
struct Node {
    int val;
    int num;
    int idx;
    Node() {
        num = 0;
        idx = -1;
    }
};
string deleteEmpty(string str)
{
    string ans;
    int n = str.length();
    for (int i = 0; i < n; ++i) {
        if (str[i] == ' ') {
            continue;
        }
        ans += str[i];
    }
    return ans;
}
bool cmp(struct Node a, struct Node b)
{
    if (a.num != b.num) {
        return a.num > b.num;
    }
    return a.idx < b.idx;
}
void deduplicationSort(string str)
{
    // 去重
    str = deleteEmpty(str);
    int idx = 0;
    struct Node number[105];
    stringstream stream(str);
    while (getline(stream, str, ',')) {
        int num = atoi(str.c_str());
        if (number[num].idx == -1) {
            number[num].idx = idx;
            number[num].val = num;
        }
        number[num].num++;
        idx++;
    }
    vector<struct Node> ans;
    for (int i = 0; i < 101; ++i) {
        if (number[i].idx != -1) {
            ans.push_back(number[i]);
        }
    }
    // 排序
    sort(ans.begin(), ans.end(), cmp);
    int n = ans.size();
    for (int i = 0; i < n; ++i) {
        if (i) {
            cout << ", ";
        }
        cout << ans[i].val;
    }
    cout<<endl;
}
int main()
{
    string str;
    while (getline(cin, str)) {
        deduplicationSort(str);
    }
    return 0;
} 
 
四、时间复杂度
时间复杂度:O(nlogn)。
在上述代码中,算法时间复杂度主要消耗在快速排序部分,快速排序的时间复杂度为 O(nlogn),所以总的时间复杂度为 O(nlogn)。
🎈 感觉有帮助记得「一键三连」支持下哦!有问题可在评论区留言💬,感谢大家的一路支持!🤞猿哥将持续输出「优质文章」回馈大家!🤞🌹🌹🌹🌹🌹🌹🤞








![[电商实时数仓] 数据仓库建模过程分析](https://img-blog.csdnimg.cn/4fe95d469dce49a9affb4b2f74ae7c73.png)
![[前端笔记——HTML 表格] 8.HTML 表格](https://img-blog.csdnimg.cn/b330ff0e83c5413ea1d75617b889ed2e.png)








