用 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.