LeetCode之“排序”:Largest Number

时间:2023-03-08 17:45:29

  题目链接

  题目要求:

  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.

  Credits:
  Special thanks to @ts for adding this problem and creating all test cases.

  在博文Leetcode:Largest Number详细题解有相对详细的分析,但本文没有参考其做法,而是参考了LeetCode论坛上的一个解决方法。具体程序如下:

 class Solution {
public:
static bool com(const int & m, const int & n)
{
return to_string(m) + to_string(n) > to_string(n) + to_string(m);
} string largestNumber(vector<int>& nums) {
string ret;
sort(nums.begin(), nums.end(), com); int sz = nums.size();
if(sz != && nums[] == )
return ""; for(int i = ; i < sz; i++)
ret += to_string(nums[i]); return ret;
}
};

  这里边值得一提的就是字符串大小比较的原理

  字符串的大小比较是逐个相应字符进行比较(比较他们的ASCII码),直到有两个字符不相等为止,ASCII码大的字母所在字符串就大,与字符串长度无关。对两个相等长度的字符串,若每个字符都比较完毕后仍相等,则两字符串相等;对不等长的字符串,若当短的字符串比较完毕时所有字符仍相等,则长度较长的字符串大!