179. Largest Number

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

Example 1:

Input: [10,2]
Output: "210"

Example 2:

Input: [3,30,34,5,9]
Output: "9534330"

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

 
AC code:
class Solution {
public:
    string largestNumber(vector<int>& nums) {
        vector<string> temp;
        string ans = "";
        for (auto num : nums) {
            temp.push_back(to_string(num));
        }
        sort(temp.begin(), temp.end(), [](string& s1, string& s2) {return s1+s2 > s2+s1;});
        for (auto i : temp) {
            ans += i;
        }
        while (ans[0] == '0' && ans.length() > 1)
            ans.erase(0, 1);
        return ans;
    }
};

Runtime: 8 ms, faster than 68.77% of C++ online submissions for Largest Number.

 

posted @ 2018-10-30 09:47  Veritas_des_Liberty  阅读(267)  评论(0编辑  收藏  举报