Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[剑指 Offer] 45. 把数组排成最小的数 #72

Open
frdmu opened this issue Aug 8, 2021 · 0 comments
Open

[剑指 Offer] 45. 把数组排成最小的数 #72

frdmu opened this issue Aug 8, 2021 · 0 comments

Comments

@frdmu
Copy link
Owner

frdmu commented Aug 8, 2021

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

 

示例 1:

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

示例 2:

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

提示:

  • 0 < nums.length <= 100

说明:

  • 输出结果可能非常大,所以你需要返回一个字符串而不是整数
  • 拼接起来的数字可能会有前导 0,最后结果不需要去掉前导 0


排序就可以解决,关键是cmp()的重写。代码如下:

class Solution {
public:
    bool static cmp(string a, string b) {
        return a+b < b+a;    
    }
    string minNumber(vector<int>& nums) {
        vector<string> tmp;
        string res;

        for (auto n: nums) {
            tmp.push_back(to_string(n));
        }
        sort(tmp.begin(), tmp.end(), cmp);
        for (auto s: tmp) {
            res += s;
        }
        
        return res;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant