数据结构与算法学习笔记

排序算法(三)



前言

本章节是排序算法的例题篇,主要展示了三个经典排序问题的求解思路和代码。


一、Kth Largest Element in an Array

1.问题描述

在一个未排序的数组中,找到第 k 大的数字。

2.输入输出样例

输入一个数组和一个目标值 k,输出第 k 大的数字。题目默认一定有解。

Input:[6,5,8,7,3,4] and k=3
Output: 6

3.解题思路与代码

可以考虑用快速选择的思想来求解,能在 O(n) 时间复杂度,O(1) 空间复杂度完成求解工作。快速选择的实现和快速排序相似,不过只需要找到第 k 大的轴即可,不需要对其左右再进行排序。

代码如下:

//将第一个数作为轴,将轴插入数组中使得轴左边数都比它小,轴右边数都比它大。
int quickSelection(vector<int>& nums, int l, int r) { 
    int i = l + 1, j = r;
    while (true) {
        while (i < r && nums[i] <= nums[l]) {  
            ++i;
        }
        while (l < j && nums[j] >= nums[l]) {
            --j;
        }
        if (i >= j) {
            break;
        }
        swap(nums[i], nums[j]);
    }
    swap(nums[l], nums[j]);
    return j;
}
//只需要找到轴就行,不用排序。
int findKthLargest(vector<int> arr, int k)
{
    int l = 0, r = arr.size() - 1, target = arr.size()-k;
    while (l < r)
    {
        int mid = quickSelection(arr, l, r);
        if (mid == target) {
            return arr[mid];
        }
        if (mid < target) { l = mid + 1; }
        else{ r = mid - 1 ; }
    }
    return arr[l];
}

二、Top K Frequent Elements

1.问题描述

给定一个数组,求前 k 个出现最频繁的数字。

2.输入输出样例

Input: nums = [1,1,1,1,2,2,3,4], k = 2
Output: [1,2]

3.解题思路与代码

可以考虑使用计数排序的思想来解题,首先对数组中所有数出现的频次进行统计,然后对频次进行排序,找到前k个最频繁的数字。由于此处数字的大小范围不定,所以可以考虑使用unordered_map来帮助搜索和查找,因为unordered_map内部实现了哈希表,因此其查找速度非常的快。使用unordered_map中的Key来表示数组中的数,Value对应其出现的频次。

代码如下:

vector<int> topKFrequent(vector<int>& nums, int k) {
    unordered_map<int, int> counts;
    int max_count = 0;
    for (const int & num : nums) {
        //找到数组中出现次数最多数的出现频次
        max_count = max(max_count, ++counts[num]);
    }
    vector<vector<int>> buckets(max_count + 1);
    for (const auto & p : counts) {
    //将unordered_map放入容器中,p.first为数组中的数,p.second为其出现的频次。
        buckets[p.second].push_back(p.first);
        cout << "p.second:" << p.second << "->" << "p.first:" << p.first << endl;
    }
    vector<int> ans;
    for (int i = max_count; i >= 0 && ans.size() < k; --i) {
    //从最大出现频次不断往下找,直到找全前k个出现频次的数
        for (const int & num : buckets[i]) {
            ans.push_back(num);
            if (ans.size() == k) {
                break;
            }
        }
    }
    return ans;
}

三、Sort Characters By Frequency

1.问题描述

给定一个字符串 s,根据字符出现的频率对其进行降序排序 。一个字符出现的频率是它出现在字符串中的次数。

2.输入输出样例

返回已排序的字符串 。如果有多个答案,返回其中任何一个。

Input:s = “tree”
Output: “eert”

3.解题思路与代码

和上一题一样,还是可以考虑使用计数排序的思想来解题。

代码如下:

//方案一:
string Solution(string s) {
    unordered_map<char, int> counts;
    int max_count = 0;
    for (const char & ch : s) {
        //找到数组中出现次数最多数的出现频次
        max_count = max(max_count, ++counts[ch]);
    }
    vector<vector<char>> buckets(max_count + 1);
    for (const auto & p : counts) {
    //将unordered_map放入容器中,p.first为数组中的数,p.second为其出现的频次。
        buckets[p.second].push_back(p.first);
        cout << "p.second:" << p.second << "->" << "p.first:" << p.first << endl;
    }
    vector<char> ans;
    for (int i = max_count; i >= 0 && ans.size() < s.length(); --i) {
    //从最大出现频次不断往下找,直到找全前k个出现频次的数
        for (const char & ch : buckets[i]){
                for(int j= i;j>0;j--){
                ans.push_back(ch);
                if (ans.size() == s.length()) {
                    break;
                }
            }
        }
    }
    //把vector<char>转换为string
    string str;
    str.assign(ans.begin(),ans.end());
    return str;
}

//速度更快,消耗内存更少的方案二:
string frequencySort(string s) {
        map<char, int> beg;
        string lastans;
        for (auto i : s) ++beg[i];
        //统计出每个字母出现的频率
        multimap<int, char> ans;
        for (auto j : beg) ans.insert({ j.second,j.first });
        //运用map自动排序
        for (auto z = ans.rbegin(); z != ans.rend(); ++z) {
            for (int _ = z->first; _ > 0; --_) lastans.push_back(z->second);}
        return lastans;
}

总结

以上就是排序算法(三)的全部内容,文章会持续更新,如果文章中有写的不对的地方,希望大家可以在评论区进行批评和指正,大家一起交流,共同进步!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猫大的救赎计划

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值