首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。