用 C++ 從數字列表中生成最大詞典順序數字的程式


假設我們有一個數字列表 nums,我們需要重新排列其順序,形成可能最大的數字,並將其作為字串返回。

因此,如果輸入類似於 nums = [20, 8, 85, 316],則輸出將為“88531620”。

為解決這個問題,我們將遵循以下步驟 -

  • 定義一個數組 temp
  • 對於 nums 中的每個專案 i
    • 以字串形式將 i 插入 temp 中
  • 根據詞典順序對陣列 temp 進行排序(檢查兩個字串 a 和 b,當 a 連線 b 大於 b 連線 a 時為 true,否則為 false)
  • 對於 temp 中的每個字串 s
    • res := res 連線 s
  • 返回 res

讓我們看以下實現以獲得更好的理解 -

示例

即時演示

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

static bool cmp(string a, string b) {
   return (a + b) >= (b + a);
}
string solve(vector<int>& nums) {
   vector<string> temp;
   for (int i : nums) {
      temp.push_back(to_string(i));
   }
   sort(temp.begin(), temp.end(), cmp);
   string res;
   for (string s : temp) {
      res += s;
   }
   return res;
}

int main(){
   vector<int> v = {20, 8, 85, 316};
   cout << solve(v);
}

輸入

{20, 8, 85, 316}

輸出

88531620

更新於:2020 年 12 月 3 日

274 次檢視

開啟你的職業生涯

完成課程後獲得官方認證

開始學習
廣告
© . All rights reserved.