自定义排序&&剑指 Offer 45. 把数组排成最小的数

本文探讨了一种非传统的排序规则,通过比较x+y与y+x来决定字符串x和y的相对大小。作者提供了两种方法,一是使用自定义函数实现的直观排序,二是利用快速排序策略。通过实例展示了如何将整数数组转换为最小数形式。
摘要由CSDN通过智能技术生成

未料到排序规则。排序规则为:若 x+y>y+x,则x”大于“y,反之,若x+y<y+x,则x”小于“y。 参考:剑指 Offer 45. 把数组排成最小的数(自定义排序,清晰图解)

定义内置函数规则:

class Solution {
public:
    string minNumber(vector<int>& nums) {
        vector<string>s;
        string res;
        for(auto num:nums){
            s.push_back(to_string(num));
        }
        sort(s.begin(),s.end(),[](string&x,string&y){return x+y<y+x;});
        for(auto x:s){
            res+=x;
        }
        return res;
    }
};

定义快速排序规则:

class Solution {
public:
    int mid(vector<string>&s,int low,int high){  //基准值
        string pivot=s[low];
        while(low<high){
            while(low<high&&(s[high]+pivot>=pivot+s[high])){
                high--;
            }
            s[low]=s[high];
            while(low<high&&(s[low]+pivot<=pivot+s[low])){
                low++;
            }
            s[high]=s[low];
        }
        s[low]=pivot;
        return low;
    }
    void quickSort(vector<string>&s,int low,int high){  //递归函数
        if(low<high){       //若小于则进入递归
            int pivot=mid(s,low,high);
            quickSort(s,low,pivot-1);
            quickSort(s,pivot+1,high);
        }
    }
    string minNumber(vector<int>& nums) {
        vector<string>s;
        string res;
        for(auto num:nums){
            s.push_back(to_string(num));
        }
        quickSort(s,0,nums.size()-1);
        for(auto x:s){
            res+=x;
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值