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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

這道題和劍指offer讀書筆記:第五章,優化時間和空間效率:問題05 把數組排成最小的數 的做法一模一樣

不過需要注意的是字符串數組頭部多餘的0要去掉,嗯嗯就這樣

#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
#include <iomanip>
#include <cstdlib>
#include <ctime>

using namespace std;


bool cmp(int a, int b)
{
    string aa = to_string(a);
    string bb = to_string(b);
    return aa + bb > bb + aa;
}

class Solution 
{
public:
    string largestNumber(vector<int>& a)
    {
        sort(a.begin(), a.end(), cmp);
        string res;
        for (int i : a)
            res += to_string(i);

        while (res.size() >= 2 && res[0] == '0')
            res.erase(res.begin());
        return res;
    }
};
發佈了716 篇原創文章 · 獲贊 30 · 訪問量 25萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章