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

这个数我拿到的第一个想法是吧数字变成字符串,然后用字符串比较。看了答案竟然用排序的函数做,排序的函数sort真的是万能的。还有在比较两个字符串的大小的时候,我的思路是一直从字符串里拿元素比较其大小,答案的做法是直接比较字符串,利用了string 的特性。还有一个问题就是注释里写的,这里又没有静态数据成员,为什么要定义静态成员函数?如果在这里用,唯一的解释是静态成员函数不属于任何的对象,它属于类。

 1 #include<iostream>
 2 #include<string>
 3 #include <vector>
 4 #include <algorithm>
 5 //#include <sstream>
 6 using namespace std;
 7 class Solution {
 8 public:
 9     string PrintMinNumber(vector<int> numbers) {
10         string res;
11         if (numbers.size() <= 0)//判断传来的vector是否为空
12             return res;
13         //string big = 0;
14         /*
15         for (int i = 0; i < numbers.size(); i++)
16         {
17             string cur = to_string(numbers[i]);
18             bool sig=comparetwo(cur, res);
19             if (sig)
20                 res = cur + res;
21             else
22                res = res + cur;
23         }
24         */
25         vector<string> st;
26         for (int i = 0; i < numbers.size(); i++)
27         {
28             string cur = to_string(numbers[i]);
29             st.push_back(cur);
30         }
31         sort(st.begin(), st.end(), comparetwo);
32 
33         for (int i = 0; i < st.size(); i++)
34         {
35             res = res + st[i];
36         }
37         return res;
38 
39     }
40     /*
41     bool comparetwo(string a, string b)
42     {
43         for (int i=0,j=0; i < a.size(), j < b.size();)
44         {
45             if (a[i] > b[j])
46                 return false;
47             else
48                 if (a[i] < b[j])
49                      return true;
50                 else
51                 {
52                     if (a[i + 1] != '')
53                         i++;
54                     if (b[j + 1] != '')
55                            j++;
56                 }
57         }
58         return true;
59     }
60     */
61     static bool comparetwo(string a, string b)//开始没有加static,报的是sort函数那一行的错误,为什么这么要加static?
62     {
63         string test1 = a + b;
64         string test2 = b + a;
65         if (test1 > test2)
66             return false;
67         else
68         {
69             return true;
70         }
71     }
72 };
73 int main()
74 {
75     Solution so;
76     vector<int> test{ 3,5,1,4,2 };
77     cout << so.PrintMinNumber(test) << endl;
78     return 0;
79 }
原文地址:https://www.cnblogs.com/neverland0718/p/11166039.html