码迷,mamicode.com
首页 > 其他好文 > 详细

Largest Number

时间:2015-01-30 01:26:21      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://blog.csdn.net/li_chihang/article/details/43287241

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!