剑指offer 面试题45 把数组排成最小的数

问题:输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。

输入:正整数数组

输出:拼接后的字符串(输出结果可能非常大,所以你需要返回一个字符串而不是整数)

思路:定义比较两个数字m,n大小的新规则,若mn<nm,则m<n,若nm<mn,则n<m。

代码:

class Solution {
public:
    static bool cmp(const string& i,const string& j)
    {
        return i+j<j+i;
    } 
    string minNumber(vector<int>& nums) {
        int len=nums.size();
        vector<string> strNum(len);
        for(int i=0;i<len;++i)
        {
            string temp=to_string(nums[i]);
            strNum[i]=temp;
        }
        sort(strNum.begin(),strNum.end(),cmp);
        string res;
        for(int i=0;i<len;++i)
            res+=strNum[i];
        return res;
    }
};

复杂度分析:时间复杂度为O(nlogn),空间复杂度为O(n).

发布了115 篇原创文章 · 获赞 14 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_22148493/article/details/105102238
今日推荐