179. Largest Number

来源:互联网 发布:海尔电视有线连接网络 编辑:程序博客网 时间:2024/06/05 13:21

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.

题意:给出一个数组,返回数组能组合的最大的数。

思路:排序的规则是:数a 和数b 对应的字符串strA, strB, 如果strA+strB>strB+strA, 则a在前,否则b在前。排好序以后,组合成一个数即可。

class Solution {public:string largestNumber(vector<int>& nums) {sort(nums.begin(), nums.end(), compare);string res;for (auto val : nums)res += to_string(val);auto pos = res.find_first_not_of('0');return (pos == string::npos ? "0" : res.substr(pos));}private:static bool compare(int a, int b){string strA = to_string(a);string strB = to_string(b);return (strA + strB > strB + strA);}};








0 0
原创粉丝点击