leetcode 179. Largest Number
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串对总大小的贡献大小
写个比较函数就可以了,注意0的情况。
1 class Solution { 2 public: 3 static bool cmp(const string& a, const string& b) { 4 return (a+b) > (b+a); 5 } 6 string largestNumber(vector<int>& nums) { 7 vector<string> v; 8 int sum = 0; 9 for (int i = 0; i < nums.size(); ++i) { 10 v.push_back(to_string(nums[i])); 11 sum += nums[i]; 12 } 13 if (sum == 0) return "0"; 14 sort(v.begin(), v.end(), cmp); 15 string k = ""; 16 for (int i = 0; i < nums.size(); ++i) { 17 k += v[i]; 18 } 19 return k; 20 } 21 };
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: