剑指 Offer 45. 把数组排成最小的数

题目描述

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

解题思路

  • 排序,对于x和y,判定大小的规则是
    • 如果xy拼接后 < yx拼接,那么x < y
  • 将排序结果从小到大拼接
  • 字符串到数字用stoistolstoll
  • 数字到字符串用to_string

知识点

数组,排序,字符串

代码

  1. class Solution {
  2. public:
  3. static bool cmp(int x, int y) {
  4. long long int xy = stoll(to_string(x) + to_string(y));
  5. long long int yx = stoll(to_string(y) + to_string(x));
  6. return xy < yx;
  7. }
  8. string minNumber(vector<int>& nums) {
  9. sort(nums.begin(), nums.end(), cmp);
  10. string res;
  11. for (const auto& n : nums) {
  12. res += to_string(n);
  13. }
  14. return res;
  15. }
  16. };