1.贪心-数组组成的最大数

问题描述

 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的特殊情况

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

熟人看不到

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值