LeetCode(179) Largest Number
Posted 逆風的薔薇
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(179) 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.
分析
把给定的整数数组,排成一个值最大的字符串。 一个很常见的问题,转换为字符串数组排序。代码
/*179. Largest Number*/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(string &s1, string &s2)
string a = s1 + s2, b = s2 + s1;
return a > b;
class Solution
public:
string largestNumber(vector<int>& nums)
if (nums.empty())
return "";
vector<string> vs;
int n = nums.size();
for (int i = 0; i < n; ++i)
char tmp[10];
snprintf(tmp, 10, "%d", nums[i]);
vs.push_back(tmp);
//for
sort(vs.begin(), vs.end(),cmp);
string ret;
for (int i = 0; i < n; ++i)
ret += vs[i];
int idx = 0,len = ret.size();
while (idx < len - 1 && ret[idx] == '0')
++idx;
return ret.substr(idx);
;
int main()
vector<int> v = 0,0 ;
cout << Solution().largestNumber(v) << endl;
system("pause");
return 0;
以上是关于LeetCode(179) Largest Number的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 179. Largest Number