CVTE笔试:最大数

CVTE的笔试题一共两道,其中一道是leecode上的最大数,具体题目如下
给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。

示例 1:

输入: [10,2]
输出: 210
示例 2:

输入: [3,30,34,5,9]
输出: 9534330
说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。
思路:
总体思路是排序,但是要注意比较的时候,要比较(string)a+b与(string)b+a的大小,例如10,2;比较102与210的大小即可
另外注意的是sort自定义的compare函数要声明为static

class Solution {
public:
	static bool compare(int a,int b)
	{
		string x="", y="";
		x += to_string(a);
		x += to_string(b);
		y += to_string(b);
		y += to_string(a);
		if (x > y)
			return true;
		else
			return false;

	}
	string largestNumber(vector<int>& nums)
	{
		if (nums.size() == 0)
			return "";

		string res = "";
		int length = nums.size();
		sort(nums.begin(), nums.end(), compare);
		for (int i = 0; i < length; ++i)
		{
			res += to_string(nums[i]);
		}
		if (res[0] == '0')
			return "0";
		return res;
	}
};

猜你喜欢

转载自blog.csdn.net/qq_43069546/article/details/88111036
今日推荐