刷题笔记-把数组排成最小的数

题目描述

https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/

解题思路

(1)首先需要将数字转化为字符串,在C++中有两种方法:

string str = to_string(num);

或者利用stringstream,但stringstream不会自动释放内存,尤其在循环中更要注意这一点:

string str;
stringstream ss;
for(auto num:nums)
{
	ss<<num;
	ss>>str;
	ss.clear();
}

(2)本题需要对字符串排序,比如“3”,“30”排序结果应为“30”,“3”,很明显303<330。设前一个字符串为a,后一个字符串为b,我们只需要判断 a+b 和 b+a 谁更大就好。可以利用内置 sort 函数进行排序,然后重新定义 compare 函数。(默认sort函数提供升序功能,本题也是升序)

bool compare(const string& a, const string& b)
{
	return a+b<b+a;
}

实现

自己写的快排函数,和字符串比较函数,肯定不及系统函数效果好了。

class Solution {
public:
    int compare(string a, string b)
    {
        int alen= a.length(), blen=b.length();
        string ab = a+b, ba = b+a;
        int i=0;
        //char ca=a[0], cb=b[0];
        while(i<alen+blen && ab[i]==ba[i]) i++;
        if(i==alen+blen) return 0;
        else if(ab[i]>ba[i]) return 1;
        else return -1;
    }

    void swap(string& a, string& b)
    {
        string temp = a;
        a = b;
        b = temp;
    }

    void QuickSort(vector<string>& strs, int l, int r){
        if(l>=r) return;
        int lc=l, rc=r;
        //l++;
        while(l<r)
        {
            while(l<r && compare(strs[r],strs[lc])>0) r--;//从右侧找比strs[lc]小的串
            while(l<r && compare(strs[l],strs[lc])<=0) l++;//从左侧找比strs[lc]大的串
            if(l!=r)
                swap(strs[l],strs[r]);
        }
        swap(strs[lc],strs[r]);
        QuickSort(strs, lc, r-1);
        QuickSort(strs, r+1, rc);
    }

    string minNumber(vector<int>& nums) {
        vector<string> strs;
        stringstream ss;
        string str,res;
        int len=nums.size();
        for(auto num: nums)
        {
            ss<<num;
            //cout<<num<<" ";
            ss>>str;
            strs.push_back(str);
            ss.clear();//stringstream不会主动释放内存,循环使用需要定时清理
            //cout<<str<<" ";
        }
        QuickSort(strs, 0, len-1);
        for(auto s:strs)
        {
            res+=s;
            //cout<<s<<" ";
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值