0
点赞
收藏
分享

微信扫一扫

数据结构 | SORT | Largest Number

夏木之下 2022-05-02 阅读 64

题目

Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: “210”
Example 2:
Input: [3,30,34,5,9]
Output: “9534330”
【输入】n个非负数,n大于1小于1000,序列n长度小于1000;
【输出】n个非负数组成的最大值。
例如:
【输入】
3 30 34 5 9
【输出】
9534330

思路

int转换为string,将字符串排序即可。用到sort函数,cmp函数比较两个字符串加在一起后的顺序。

代码

#include <bits/stdc++.h>
using namespace std;

class LargestNumber 
{
public:
    string largestNumber(vector<int> &nums);
    static bool cmp(string &fir, string &sec);
};

int main()
{
    vector<int> mylist;
    int item;
    string num;
    while (cin >> item)
    {
        mylist.push_back(item);
    }
    LargestNumber sol;
    num = sol.largestNumber(mylist);
    cout << num << endl;
    system("pause");
    return 0;
}

string LargestNumber::largestNumber(vector<int> &nums)
{
    int size = nums.size();
    vector<string> str;
    for(int i = 0; i < size; i++)
    {
        str.push_back(to_string(nums[i]));//转化为string
    }
    sort(str.begin(), str.end(), cmp);
    int strSize = str.size();
    string ans;
    for(int i = 0; i < strSize; i++)
    {
        ans += str[i];
    }
    return ans;
}

bool LargestNumber::cmp(string &fir, string &sec)
{
    return (fir + sec) > (sec + fir);//true即fir+sec形式更大,参数里fir放前边
}

一些问题

  1. 比较函数中,结果为true即fir+sec形式更大,参数里前边的就放在前边。
  2. 用了vector分别放入intstring,使用to_string函数。
  3. sort(str.begin(),str.end(),cmp)sort的用法。
举报

相关推荐

0 条评论