问题描述
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.
翻译
最大数。给定一串非负整数,将它们排列成最大的数。
例如,给定 [3,30,34,5,9],最大的数字是 9534330。
注意:结果可能非常大,因此需要返回字符串而不是整数。
//字典序最大
思路
局部字典序最大
代码
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string>
#include <algorithm>
#include <stdlib.h>
#include <vector>
using namespace std;
const int N = 1e6 + 10;
bool cmp(string a,string b )
{
return a + b > b + a;//比较字典序
}
//核心 字典序最小
int main()
{
int n;
cout << "Please enter the number of the arr :" << endl;
cin >> n;
cout << "Please enter the arr :" << endl;
vector<string> s;
for (int i = 1; i <= n; i++)
{
string tem;
cin >> tem;
s.push_back(tem);
}
sort(s.begin(), s.end(), cmp);
string ans = "";
for (string ele : s)
ans += ele;
if (ans[0] == '0')//0 0 时输出0
ans = "0";
cout << "The largest number is " <<ans <<endl;
return 0;
}
测试案例
运行结果
时间复杂度分析
只使用了一个循环来遍历数组,在sort函数中使用归并排序,耗费nlogn
所以总时间是O(nlogn)
速记
记住cmp中的内容,以及等于0的特殊情况