[LeetCode] Largest Number

Well, this problem is designed for radix sort. For more information about radix sort, Introduction to Algorithms, 3rd edition has some nice examples.

However, it can be solved simply by using the sort function while defining a new comparison function for it.

The code is pretty straight-forward.

 1     static bool cmp(int s, int t) {
 2         return to_string(s) + to_string(t) > to_string(t) + to_string(s);
 3     }
 4     string largestNumber(vector<int>& nums) {
 5         sort(nums.begin(), nums.end(), cmp);
 6         string ans;
 7         for (int i = 0; i < (int)nums.size(); i++)
 8             ans += to_string(nums[i]);
 9         if (ans[0] == '0') return "0";
10         return ans;
11     }
posted @ 2015-06-09 17:13  jianchao-li  阅读(152)  评论(0编辑  收藏  举报