首页 > 代码库 > Largest Number

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.

解题思路:首先将Int转化为字符串,定义一个字符串的排序标准进行排序;

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<sstream>
using namespace std;
bool CompareString(const string &s1,const string &s2)
{
	return (s1 + s2) > (s2 + s1);          //  比较标准
}
void Fast_short(vector<string>&NumStrVector, int begin, int end, bool(*compare)(const string &, const string &))
{
	if (begin<end){
		string target = NumStrVector[end];
		int    s = begin;
		for (int idx = begin; idx != end;++idx){
			if (compare(NumStrVector[idx],target))
			{
				string tmp = NumStrVector[s];
				NumStrVector[s] = NumStrVector[idx];
				NumStrVector[idx] = tmp;
				++s;	
			}
		}
		string tmp = NumStrVector[s];
		NumStrVector[s] = NumStrVector[end];
		NumStrVector[end] = tmp;
		Fast_short(NumStrVector, begin, s-1, compare);
		Fast_short(NumStrVector, s + 1, end, compare);
	}
}
string largestNumber(vector<int> &num) {
	vector<string>NumStrVector(num.size());
	for (int i = 0; i != num.size();++i){
		stringstream ss;
		ss << num[i];
		ss >> NumStrVector[i];
	}
	if (NumStrVector.size() == 1)
		return NumStrVector[0];
	Fast_short(NumStrVector,0,NumStrVector.size()-1, CompareString);
	//sort(NumStrVector.begin(), NumStrVector.end(), CompareString);
	string ResultStr;
	for_each(NumStrVector.begin(), NumStrVector.end(), [&ResultStr](const string s){ResultStr += s; });
	for (int i = 0; i != ResultStr.size();++i){        //前置0情况处理
		if (ResultStr[i] != '0')
			return ResultStr.substr(i);
	}
	return ResultStr.substr(ResultStr.size() - 1);
}



Largest Number