题目描述:

Given a list of non negative integers, arrange them such that they form the largest number.

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

Note: The result may be very large, so you need to return a string instead of an integer.

解题思路:

可以先把int数组转化为string数组,然后再写一个sort函数用的cmp函数,如果字符串a+b>b+a,则不变位置,否则换位置.用sort函数对数组进行排序,最后再把所有字符串相加.

代码:

 1 class Solution {
 2 public:
 3     string largestNumber(vector<int>& nums) {
 4         int n=nums.size();
 5         vector<string> str(n);
 6         for(int i=0;i<n;++i)
 7         //将int数组转换为字符串数组
 8         {
 9             str[i] = to_string(nums[i]);
10         }
11         sort(str.begin(), str.end(), cmp);  //排序
12         string res = "";
13         for(int i=0;i<n;i++)
14         {
15             res += str[i];
16         }
17         if(res[0]=='0')
18         //如果开头是'0'就说明这个字符串全为'0',只要返回"0"即可
19             return "0";
20         return res;
21 
22     }
23     static bool cmp(string strnum1, string strnum2)
24     {
25         string str1 = strnum1+strnum2;
26         string str2 = strnum2+strnum1;
27         return str1>str2;
28     }
29 };

 

posted on 2018-04-04 21:32  宵夜在哪  阅读(80)  评论(0编辑  收藏  举报