题目:
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.
题解:
自写comparator用于排序: str(a) + str(b) > str(b) + str(a)。注意结果连续个零的情况,只需返回一个0。Java需要高级语言操作,以后学来了再补上。
C++版:
class Solution { public: string largestNumber(vector<int>& nums) { if(nums.size() == 0) return ""; sort(nums.begin(), nums.end(), compare); string result = to_string(nums[0]); for(int i = 1; i < nums.size(); i++) { result += to_string(nums[i]); } if(result[0] == '0') return "0"; return result; } static bool compare(int a, int b) { return to_string(a) + to_string(b) > to_string(b) + to_string(a); } };
class Solution: # @param {integer[]} nums # @return {string} def largestNumber(self, nums): strings = sorted([str(i) for i in nums], cmp = self.compare) result = "".join(strings).lstrip('0') return result or '0' def compare(self, a, b): return [1, -1][a + b > b + a]