LCOF劍指offer--面試題45. 把數組排成最小的數

輸入一個非負整數數組,把數組裏所有數字拼接起來排成一個數,打印能拼接出的所有數字中最小的一個。

示例 1:

輸入: [10,2]
輸出: "102"

示例 2:

輸入: [3,30,34,5,9]
輸出: "3033459"

提示:

0 < nums.length <= 100
說明:

輸出結果可能非常大,所以你需要返回一個字符串而不是整數
拼接起來的數字可能會有前導 0,最後結果不需要去掉前導 0
通過次數12,405提交次數22,270

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
分析:
根據排序規則,自定義sort
解答:

class Solution {
public:
    static bool cmp(string a, string b){
            string ab = a + b;
            string ba = b + a;
            if(ab<ba){
                return true;
            }

            return false;
    }
    string minNumber(vector<int>& nums) {
        vector<string> numstr;
        string result;

        for(auto num:nums){
            numstr.push_back(to_string(num));
        }

        sort(numstr.begin(),numstr.end(),cmp);

        for(auto s:numstr){
            result.append(s);
        }

        return result;

    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章