LeetCode *** 179. Largest Number (sort的使用。。。)

来源:互联网 发布:电脑屏幕自动截图软件 编辑:程序博客网 时间:2024/05/17 20:30

题目:

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 is9534330.

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


分析:


代码:

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


0 0
原创粉丝点击