[LeetCode]Largest Number拼接成最大的数字

触宝笔试题
题目意思是给你一组数字,例如:

[3, 30, 34, 5, 9]

那么所能拼成的最大数字应该是:

9534330

搜了下又是LeetCode的题!

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.

惭愧,我自己完全没有思路。不过已经有博主写的非常好了,下面是链接
算法学习 - 拼接成最大的数字

具体内容我就不复制过来,但是此博主是用C++11写的,我自己的编译器还不支持11,所以我做的时候有些改动,
1.to_string函数,这个需要改,这篇博文里写的挺好的,C++中int型与string型互相转换

2.sort算法中用到了max函数,这个是博主自定义的,但是我运行的时候发现提示

 error: no matching function for call to 'sort(std::vector<int>::iterator, std::vector<int>::iterator, <unresolved overloaded function type>)'

应该是由于algorithm里含有max函数的问题,将自己定义的max随便改个名就好了。

最后完整的程序如下

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
// #include <cstdio>
// #include <cstdlib>
#include <cmath>
#include <ctime>
#include <cassert>
#include <numeric>
#include <algorithm>
#include <functional>
using namespace std;

string getstring(const int n)
{
    stringstream newstr;
    newstr << n;
    return newstr.str();
}

// bool max(vector<int>::iterator lhs, vector<int>::iterator rhs)
// {
//     return lhs < rhs;
// }

static bool my_max(int a, int b)
{
    string s1 = getstring(a) + getstring(b);
    string s2 = getstring(b) + getstring(a);
    return (s1.compare(s2) > 0);
}

string largestNum(vector<int> &num)
{
    string s = "";
    sort(num.begin(), num.end(), my_max);
    // sort(num.rbegin(), num.rend());
    // qsort(num, num.size(), sizeof(int), max);
    if (num[0] == 0)
    {
        return "0";
    }
    for (int i = 0; i < num.size(); ++i)
    {
        s.append(getstring(num[i]));
    }
    return s;
}

int main(int argc, char const *argv[])
{
    // int i = 123;
    // string s = getstring(i);
    // cout << s << endl;
    vector<int> v;
    v.push_back(3);
    v.push_back(34);
    v.push_back(30);
    v.push_back(5);
    v.push_back(9);
    cout << largestNum(v) << endl; //9534330
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值