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.
对应剑指Offer上33题,把数组排成最小的数,思路一致。
思路一:输出所有的全排列,进行比较输出最大的数。
思路二:参考剑指offer,寻找一个排序规则,判断两个数m和n哪个应该排在前面。若mn>nm,,则m排在n前面,mn<nm,则m排在n后面。排好序直接输出。
class Solution { public: static bool compare(int a,int b){ //应定义为静态函数,目前还不知道原因 return to_string(a) + to_string(b) > to_string(b) + to_string(a); } string largestNumber(vector<int>& nums) { string result; if(nums.empty()){ return result; } sort(nums.begin(),nums.end(),compare); for(auto num:nums){ result+=to_string(num); } return result[0] == '0'? "0":result; //[0,0]应返回“0”而不是“00” } }; //more about lambda,you can reference:http://blog.csdn.net/taoyanqi8932/articl class Solution { public: string largestNumber(vector<int> &num) { sort(num.begin(), num.end(), [](int a, int b){ return to_string(a)+to_string(b) > to_string(b)+to_string(a); }); string ans; for(int i=0; i<num.size(); i++){ ans += to_string(num[i]); } return ans[0]=='0' ? "0" : ans; } };GitHub-Leetcode: https://github.com/wenwu313/LeetCode