剑指offer:把数组排成最小的数

题目描述:

输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。

思路分析:

正常的思路是用一个全排列,那么复杂度为O(n!)。

这里实际要考察的是一个排序的方式。试想对于每两个数,例如3,32,可以拼成332和323,那么显然此时在这个问题当中32排在3前面更好。因此就实现一个比较函数,实现这个比较。同时注意需要将整数转换为字符串后可以直接拼接,这里用的是头文件<string>当中的to_string函数。具体的实现看代码。

代码:

 1 class Solution {
 2 public:
 3     string PrintMinNumber(vector<int> numbers) {
 4         int len = numbers.size();
 5         if(len<=0)
 6             return "";
 7         sort(numbers.begin(), numbers.end(), cmp);
 8         string res;
 9         for(int i=0; i<len; i++)
10             res += to_string(numbers[i]);
11         return res;
12     }
13 private:
14     static bool cmp(int a, int b)
15     {
16         string A = to_string(a)+to_string(b);
17         string B = to_string(b)+to_string(a);
18         return A<B;
19     }
20 };
原文地址:https://www.cnblogs.com/LJ-LJ/p/11100356.html